本文整理汇总了Java中com.google.gson.Gson类的典型用法代码示例。如果您正苦于以下问题:Java Gson类的具体用法?Java Gson怎么用?Java Gson使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
Gson类属于com.google.gson包,在下文中一共展示了Gson类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: apiTagsCreate
import com.google.gson.Gson; //导入依赖的package包/类
/**
* 创建用户标签
*
* @param name
* @return
* @throws ClientProtocolException
* @throws URISyntaxException
* @throws IOException
* @throws AccessTokenFailException
*/
public TagsCreateResp apiTagsCreate(String name)
throws ClientProtocolException, URISyntaxException, IOException, AccessTokenFailException {
MpAccessToken token = mpApi.apiToken();
String path = String.format("/tags/create?access_token=%s", token.getAccessToken());
TreeMap<String, Object> tag = new TreeMap<String, Object>();
tag.put("name", name);
TreeMap<String, Object> reqMap = new TreeMap<String, Object>();
reqMap.put("tag", tag);
String respText = HttpUtil.post(mpApi.config.getApiHttps(), path, reqMap);
TagsCreateResp resp = new Gson().fromJson(respText, TagsCreateResp.class);
if (mpApi.log.isInfoEnabled()) {
mpApi.log.info(String.format("apiTagsCreate %s", new Gson().toJson(resp)));
}
return resp;
}
示例2: performSerializeTests
import com.google.gson.Gson; //导入依赖的package包/类
private void performSerializeTests() {
mBarChart.clear();
mBarChart.setSections(new String[] {"Serialize 60 items", "Serialize 20 items", "Serialize 7 items", "Serialize 2 items"});
Gson gson = new Gson();
ObjectMapper objectMapper = new ObjectMapper();
Moshi moshi = new Moshi.Builder().build();
List<Serializer> serializers = new ArrayList<>();
for (Response response : mResponsesToSerialize) {
for (int iteration = 0; iteration < ITERATIONS; iteration++) {
serializers.add(new GsonSerializer(mSerializeListener, response, gson));
serializers.add(new JacksonDatabindSerializer(mSerializeListener, response, objectMapper));
serializers.add(new LoganSquareSerializer(mSerializeListener, response));
serializers.add(new MoshiSerializer(mSerializeListener, response, moshi));
}
}
for (Serializer serializer : serializers) {
serializer.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
}
}
示例3: getData
import com.google.gson.Gson; //导入依赖的package包/类
public void getData() {
LoginData loginData = (LoginData) aCache.getAsObject(ACacheKey.CURRENT_ACCOUNT);
addSubscription(apiStores.GetCsgData(loginData.getToken(), 1, 3), new ApiCallback<BaseModel<JsonArray>>(delegate.getActivity()) {
@Override
public void onSuccess(BaseModel<JsonArray> model) {
// ToastUtil.showToast("请求成功" + model.getData().toString(), delegate.getActivity());
// delegate.setData(model.getData());
F.e(model.getData().toString());
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
ArrayList<CSGDynamic> datas = gson.fromJson(model.getData(), new TypeToken<ArrayList<CSGDynamic>>() {
}.getType());
delegate.setData(datas);
}
@Override
public void onFailure(String msg) {
ToastUtil.showToast(msg, delegate.getActivity());
}
@Override
public void onFinish() {
}
});
}
示例4: getPairedDeviceMicroBit
import com.google.gson.Gson; //导入依赖的package包/类
public static BluetoothDevice getPairedDeviceMicroBit(Context context) {
SharedPreferences pairedDevicePref = context.getApplicationContext().getSharedPreferences(PREFERENCES_KEY,
Context.MODE_MULTI_PROCESS);
if(pairedDevicePref.contains(PREFERENCES_PAIREDDEV_KEY)) {
String pairedDeviceString = pairedDevicePref.getString(PREFERENCES_PAIREDDEV_KEY, null);
Gson gson = new Gson();
sConnectedDevice = gson.fromJson(pairedDeviceString, ConnectedDevice.class);
//Check if the microbit is still paired with our mobile
BluetoothAdapter mBluetoothAdapter = ((BluetoothManager) MBApp.getApp().getSystemService(Context
.BLUETOOTH_SERVICE)).getAdapter();
if(mBluetoothAdapter.isEnabled()) {
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
for(BluetoothDevice bt : pairedDevices) {
if(bt.getAddress().equals(sConnectedDevice.mAddress)) {
return bt;
}
}
}
}
return null;
}
示例5: testDeserializationWithMultipleTypes
import com.google.gson.Gson; //导入依赖的package包/类
@Test
public void testDeserializationWithMultipleTypes() {
GsonBuilder gsonBuilder = new GsonBuilder();
new GraphAdapterBuilder().addType(Company.class).addType(Employee.class)
.registerOn(gsonBuilder);
Gson gson = gsonBuilder.create();
String json = "{'0x1':{'name':'Google','employees':['0x2','0x3']},"
+ "'0x2':{'name':'Jesse','company':'0x1'},"
+ "'0x3':{'name':'Joel','company':'0x1'}}";
Company company = gson.fromJson(json, Company.class);
assertEquals("Google", company.name);
Employee jesse = company.employees.get(0);
assertEquals("Jesse", jesse.name);
assertEquals(company, jesse.company);
Employee joel = company.employees.get(1);
assertEquals("Joel", joel.name);
assertEquals(company, joel.company);
}
示例6: danMuAdd
import com.google.gson.Gson; //导入依赖的package包/类
@PostMapping("/add")
@ResponseBody
public String danMuAdd() {
Map<String, String> user = new HashMap<>();
DanMu danMu = new DanMu();
String userName = DMClient.getName();
String userText = DMClient.getText();
danMu.setName(userName);
danMu.setText(userText);
if(userName == null)
return null;
if (userName.equals(preName)) {
return null;
}
preName = userName;
dmRepository.save(danMu);
Gson gson = new Gson();
user.put("name", userName);
user.put("text", userText);
String gsonStr = gson.toJson(user);
return gsonStr;
}
示例7: replace
import com.google.gson.Gson; //导入依赖的package包/类
/**
* Replaces an existing Forge account in the storage
*
* @param context calling context
* @param account the Forge account to replace the original with
* @return the account added to the storage, if it's a failure returns null
*/
public static ForgeAccount replace(Context context, ForgeAccount account) {
// Initialise GSON
Gson gson = new Gson();
// Get the already saved Forge accounts
HashMap<UUID, ForgeAccount> accounts = FileManager.load(context);
// Replace the account with the matching UUID with the new account details
accounts.put(account.getId(), account);
// Convert the list of Forge Accounts to a JSON string
String jsonString = gson.toJson(new ArrayList<>(accounts.values()));
// Internal save
FileOutputStream outputStream;
try {
// Save the JSON to the file
outputStream = context.openFileOutput(context.getString(R.string.filename_forge_accounts), Context.MODE_PRIVATE);
outputStream.write(jsonString.getBytes());
outputStream.close();
return account;
} catch (Exception e) {
// If there is an error, log it
Log.e(Forge.ERROR_LOG, e.getMessage());
return null;
}
}
示例8: getJsonObject
import com.google.gson.Gson; //导入依赖的package包/类
/**
* Gets a JsonObject by calling apiUrl and parsing the JSON response String. This method accepts
* a Map that can contain custom headers to include in the request.
*
* @param client The OkHTTP client to use to make the request
* @param gson The GSON instance to use to parse the response String
* @param apiUrl The URL to call to get the response from
* @param headersMap The headers to include in the request. Can be null to not add any headers
* @return A JsonObject representation of the API response, null when there was an error or
* Exception thrown by the HTTP call
*/
public static JsonObject getJsonObject(final OkHttpClient client, final Gson gson,
final String apiUrl, @Nullable final Map<String, String> headersMap) {
if (client == null || gson == null || TextUtils.isEmpty(apiUrl)) return null;
Request.Builder builder = new Request.Builder().url(apiUrl);
if (headersMap != null && headersMap.size() > 0) {
// Add headers to the request if headers are available
for (Map.Entry<String, String> entry : headersMap.entrySet()) {
builder.addHeader(entry.getKey(), entry.getValue());
}
}
Request request = builder.build();
try {
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
ResponseBody responseBody = response.body();
String json = responseBody.string();
responseBody.close();
return gson.fromJson(json, JsonObject.class);
} catch (JsonSyntaxException | IOException e) {
LogUtil.e(e, "Error " + apiUrl);
}
return null;
}
示例9: RemoteCommentService
import com.google.gson.Gson; //导入依赖的package包/类
public RemoteCommentService() {
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient httpClient = new OkHttpClient.Builder()
.addInterceptor(loggingInterceptor)
.build();
Gson gson = new GsonBuilder()
.excludeFieldsWithoutExposeAnnotation()
.create();
retrofit = new Retrofit.Builder()
.client(httpClient)
.baseUrl(BuildConfig.API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
}
示例10: loadProfileInformation
import com.google.gson.Gson; //导入依赖的package包/类
public void loadProfileInformation() {
NavigationView navigationView = (NavigationView) findViewById(R.id.navigationView);
View header = navigationView.getHeaderView(0);
textView_profile_id = (TextView) header.findViewById(R.id.textViewProfileId);
textView_profile_name = (TextView) header.findViewById(R.id.textViewProfileName);
textView_profile_phone = (TextView) header.findViewById(R.id.textViewProfilePhone);
Gson gson = new Gson();
String json = sharedPreferencesProfileInformation.getString("currentUser", "");
currentUser = gson.fromJson(json, User.class);
textView_profile_id.setText(String.valueOf(currentUser.getId()));
textView_profile_name.setText(currentUser.getFname() + " " + currentUser.getLname());
textView_profile_phone.setText(currentUser.getPhone());
}
示例11: rxCreateDiskObservable
import com.google.gson.Gson; //导入依赖的package包/类
public static <T> Observable rxCreateDiskObservable(final String key, final Class<T> clazz) {
return Observable.create(new Observable.OnSubscribe<String>() {
@Override
public void call(Subscriber<? super String> subscriber) {
LogUtils.d("get data from disk: key==" + key);
String json = ACache.get(ReaderApplication.getsInstance()).getAsString(key);
LogUtils.d("get data from disk finish , json==" + json);
if (!TextUtils.isEmpty(json)) {
subscriber.onNext(json);
}
subscriber.onCompleted();
}
})
.map(new Func1<String, T>() {
@Override
public T call(String s) {
return new Gson().fromJson(s, clazz);
}
})
.subscribeOn(Schedulers.io());
}
示例12: extractEmptyBranchTest
import com.google.gson.Gson; //导入依赖的package包/类
@Test
public void extractEmptyBranchTest() throws ApiException, IOException, URISyntaxException {
List<String> branch = Arrays.asList("root", "elt1");
File temp = File.createTempFile("tempfile", ".tmp");
ProcessGroupFlowEntity response = TestUtils.createProcessGroupFlowEntity("idComponent", "nameComponent");
when(processGroupServiceMock.changeDirectory(branch)).thenReturn(Optional.of(response));
when(flowapiMock.getControllerServicesFromGroup("idComponent")).thenReturn(new ControllerServicesEntity());
extractService.extractByBranch(branch, temp.getAbsolutePath());
//evaluate response
Gson gson = new Gson();
try (Reader reader = new InputStreamReader(new FileInputStream(temp), "UTF-8")) {
GroupProcessorsEntity result = gson.fromJson(reader, GroupProcessorsEntity.class);
assertTrue(result.getProcessors().isEmpty());
assertTrue(result.getGroupProcessorsEntity().isEmpty());
assertEquals("nameComponent", result.getName());
}
}
示例13: convertJSON
import com.google.gson.Gson; //导入依赖的package包/类
@Override
public void convertJSON(String json) {
Gson gson = new Gson();
OrderDAO order = gson.fromJson(json, OrderDAO.class);
this.orderId = order.getOrderId();
this.orderSender = order.getOrderSender();
this.orderReceiver = order.getOrderReceiver();
this.acceptTime = order.getAcceptTime();
this.title = order.getTitle();
this.publicDetails = order.getPublicDetails();
this.privateDetails = order.getPrivateDetails();
this.requestTime = order.getRequestTime();
this.orderState = order.getOrderState();
this.price = order.getPrice();
this.contact = order.getContact();
this.completeTime = order.getCompleteTime();
}
示例14: provideRedditResource
import com.google.gson.Gson; //导入依赖的package包/类
@Provides
public RedditResource provideRedditResource() {
Type redditPostListType = new TypeToken<List<RedditPost>>() {}.getType();
Gson gson = new GsonBuilder()
.registerTypeAdapter(redditPostListType, new RedditPostsDeserializer())
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://www.reddit.com/")
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
return retrofit.create(RedditResource.class);
}
示例15: getBadges
import com.google.gson.Gson; //导入依赖的package包/类
@Override
public Badge[] getBadges() throws Exception {
List<Badge> badges = new ArrayList<>();
String url = "https://www.roblox" +
".com/users/inventory/list-json?assetTypeId=21&cursor=&itemsPerPage=100" +
"&pageNumber=1&sortOrder=Desc&userId=" + this.getUserId();
BadgesResponse response = new Gson().fromJson(Jsoup.connect(url).ignoreContentType(true)
.get().body().text(), BadgesResponse.class);
for (BadgesResponse.BadgesData.PlayerBadgeData item : response.Data.Items) {
badges.add(new Badge(item.Item.AssetId, item.Item.Name));
}
// next page
if (response.Data.nextPageCursor != null) {
badges.addAll(recursiveBadgeRetrieve(response));
}
return badges.toArray(new Badge[badges.size()]);
}