com.google.gson.Gson.fromJson()方法的使用及代码示例

x33g5p2x  于2022-01-19 转载在 其他  
字(11.2k)|赞(0)|评价(0)|浏览(393)

本文整理了Java中com.google.gson.Gson.fromJson()方法的一些代码示例,展示了Gson.fromJson()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Gson.fromJson()方法的具体详情如下:
包路径:com.google.gson.Gson
类名称:Gson
方法名:fromJson

Gson.fromJson介绍

[英]This method deserializes the Json read from the specified parse tree into an object of the specified type. It is not suitable to use if the specified class is a generic type since it will not have the generic type information because of the Type Erasure feature of Java. Therefore, this method should not be used if the desired type is a generic type. Note that this method works fine if the any of the fields of the specified object are generics, just the object itself should not be a generic type. For the cases when the object is of generic type, invoke #fromJson(JsonElement,Type).
[中]此方法将从指定解析树读取的Json反序列化为指定类型的对象。如果指定的类是泛型类型,则不适合使用它,因为由于Java的类型擦除功能,它将不具有泛型类型信息。因此,如果所需类型是泛型类型,则不应使用此方法。请注意,如果指定对象的任何字段都是泛型,则此方法可以正常工作,只是对象本身不应是泛型类型。对于对象为泛型类型的情况,请调用#fromJson(JsonElement,type)。

代码示例

代码示例来源:origin: stackoverflow.com

Gson gson = new Gson();
String json = mPrefs.getString("MyObject", "");
MyObject obj = gson.fromJson(json, MyObject.class);

代码示例来源:origin: stackoverflow.com

Gson g = new Gson();

Person person = g.fromJson("{\"name\": \"John\"}", Person.class);
System.out.println(person.name); //John

System.out.println(g.toJson(person)); // {"name":"John"}

代码示例来源:origin: gocd/gocd

private ResponseScratch parseResponseForMigration(String responseBody) {
  return new GsonBuilder().create().fromJson(responseBody, ResponseScratch.class);
}

代码示例来源:origin: stackoverflow.com

Map<String, String> myMap = new HashMap<String, String>();
myMap.put("one", "hello");
myMap.put("two", "world");

Gson gson = new GsonBuilder().create();
String json = gson.toJson(myMap);

System.out.println(json);

Type typeOfHashMap = new TypeToken<Map<String, String>>() { }.getType();
Map<String, String> newMap = gson.fromJson(json, typeOfHashMap); // This type must match TypeToken
System.out.println(newMap.get("one"));
System.out.println(newMap.get("two"));

代码示例来源:origin: stackoverflow.com

Gson gson = new Gson();
Pojo pojo = gson.fromJson(jsonInput2, Pojo.class);
System.out.println(pojo);

代码示例来源:origin: stackoverflow.com

Gson gson=  new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").create();
 String date = "\"2013-02-10T13:45:30+0100\"";
 Date test = gson.fromJson(date, Date.class);
 System.out.println("date:" + test);

代码示例来源:origin: stackoverflow.com

new GsonBuilder()
  .registerTypeAdapter(TestAnnotationBean.class, new AnnotatedDeserializer<TestAnnotationBean>())
  .create();
TestAnnotationBean tab = gson.fromJson(json, TestAnnotationBean.class);
System.out.println(tab.foo);
System.out.println(tab.bar);
tab = gson.fromJson(json, TestAnnotationBean.class);
System.out.println(tab.foo);
System.out.println(tab.bar);
tab = gson.fromJson(json, TestAnnotationBean.class);
System.out.println(tab.foo);
System.out.println(tab.bar);
T pojo = new Gson().fromJson(je, type);

代码示例来源:origin: SonarSource/sonarqube

public static void format(String json) {
 JsonObject jsonElement = new Gson().fromJson(json, JsonObject.class);
 JsonArray webServices = (JsonArray) jsonElement.get("webServices");
  String webServicePath = webService.get("path").getAsString();
   System.out.println("Excluding WS " + webServicePath + " from code generation");
   continue;
  writeSourceFile(helper.packageInfoFile(webServicePath), applyTemplate("package-info.vm", webServiceContext));
  for (JsonElement actionElement : (JsonArray) webService.get("actions")) {
   JsonObject action = (JsonObject) actionElement;

代码示例来源:origin: stackoverflow.com

//from object to JSON 
Gson gson = new Gson();
gson.toJson(yourObject);

// from JSON to object 
yourObject o = gson.fromJson(JSONString,yourObject.class);

代码示例来源:origin: ctripcorp/apollo

private String mockLongPollBody(String notificationsStr) {
 List<ApolloConfigNotification> oldNotifications = gson.fromJson(notificationsStr, notificationType);
 List<ApolloConfigNotification> newNotifications = new ArrayList<>();
 for (ApolloConfigNotification notification : oldNotifications) {
  newNotifications
    .add(new ApolloConfigNotification(notification.getNamespaceName(), notification.getNotificationId() + 1));
 }
 return gson.toJson(newNotifications);
}

代码示例来源:origin: bwssytems/ha-bridge

public List<HomeWizardSmartPlugDevice> getDevices() 
{
  List<HomeWizardSmartPlugDevice> homewizardDevices = new ArrayList<>();	
  try {
    
    String result = requestJson(EMPTY_STRING);
    JsonParser parser = new JsonParser();
    JsonObject resultJson = parser.parse(result).getAsJsonObject();
    cloudPlugId = resultJson.get("id").getAsString();
  
    String all_devices_json = resultJson.get("devices").toString();
    Device[] devices = gson.fromJson(all_devices_json, Device[].class);
    
    // Fix names from JSON
    for (Device device : devices) {
      device.setTypeName(StringUtils.capitalize(device.getTypeName().replace("_", " ")));
      homewizardDevices.add(mapDeviceToHomeWizardSmartPlugDevice(device));
    }
  }
  catch(Exception e) {
    log.warn("Error while get devices from cloud service ", e);
  }
  
  log.info("Found: " + homewizardDevices.size() + " devices");
  return homewizardDevices;
}

代码示例来源:origin: chanjarster/weixin-java-tools

@Override
public List<WxMpUserSummary> getUserSummary(Date beginDate, Date endDate) throws WxErrorException {
 String url = "https://api.weixin.qq.com/datacube/getusersummary";
 JsonObject param = new JsonObject();
 param.addProperty("begin_date", SIMPLE_DATE_FORMAT.format(beginDate));
 param.addProperty("end_date", SIMPLE_DATE_FORMAT.format(endDate));
 String responseContent = post(url, param.toString());
 JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent)));
 return WxMpGsonBuilder.INSTANCE.create().fromJson(tmpJsonElement.getAsJsonObject().get("list"),
   new TypeToken<List<WxMpUserSummary>>() {
   }.getType());
}

代码示例来源:origin: iSoron/uhabits

@NonNull
public Command parse(@NonNull String json)
    .fromJson(json, ArchiveHabitsCommand.Record.class)
    .toCommand(habitList);
    .fromJson(json, ChangeHabitColorCommand.Record.class)
    .toCommand(habitList);
    .fromJson(json, CreateHabitCommand.Record.class)
    .toCommand(modelFactory, habitList);
    .fromJson(json, CreateRepetitionCommand.Record.class)
    .toCommand(habitList);
    .fromJson(json, DeleteHabitsCommand.Record.class)
    .toCommand(habitList);
    .fromJson(json, EditHabitCommand.Record.class)
    .toCommand(modelFactory, habitList);
    .fromJson(json, ToggleRepetitionCommand.Record.class)
    .toCommand(habitList);
    .fromJson(json, UnarchiveHabitsCommand.Record.class)
    .toCommand(habitList);

代码示例来源:origin: Qihoo360/XLearning

set(CONTAINER_NUMBER, String.valueOf(0));
} else {
 Gson gson = new Gson();
 Map<String, Object> readLog = new TreeMap<>();
 readLog = (Map) gson.fromJson(line, readLog.getClass());
 int i = 0;
 int workeri = 0;
          }).create();
      ConcurrentHashMap<String, Object> map = gson2.fromJson(cpuMetrics, type);
      if (map.size() > 0) {
       cpuMetricsFlag = true;
       if (containerMessage.get(AMParams.CONTAINER_ROLE).equals(XLearningConstants.WORKER) || containerMessage.get(AMParams.CONTAINER_ROLE).equals(XLearningConstants.EVALUATOR)) {
        set("workerCpuMemMetrics" + workeri, new Gson().toJson(map.get("CPUMEM")));
        if (map.containsKey("CPUUTIL")) {
         set("workerCpuUtilMetrics" + workeri, new Gson().toJson(map.get("CPUUTIL")));
        set("psCpuMemMetrics" + psi, new Gson().toJson(map.get("CPUMEM")));
        if (map.containsKey("CPUUTIL")) {
         set("psCpuUtilMetrics" + psi, new Gson().toJson(map.get("CPUUTIL")));
      Type type = new TypeToken<Map<String, List<Double>>>() {
      }.getType();
      Map<String, List<Double>> map = new Gson().fromJson(cpuStatistics, type);
      if (map.size() > 0) {
       if (containerMessage.get(AMParams.CONTAINER_ROLE).equals(XLearningConstants.WORKER) || containerMessage.get(AMParams.CONTAINER_ROLE).equals(XLearningConstants.EVALUATOR)) {

代码示例来源:origin: aa112901/remusic

public static MusicDetailInfo getInfo(final String id) {
  MusicDetailInfo info = null;
  try {
    JsonObject jsonObject = HttpUtil.getResposeJsonObject(BMA.Song.songBaseInfo(id).trim()).get("result")
        .getAsJsonObject().get("items").getAsJsonArray().get(0).getAsJsonObject();
    info = MainApplication.gsonInstance().fromJson(jsonObject, MusicDetailInfo.class);
  } catch (Exception e) {
    e.printStackTrace();
  }
  return info;
}

代码示例来源:origin: apache/incubator-gobblin

private static Set<SourceEntity> getSourceEntities(String response) {
 Set<SourceEntity> result = Sets.newHashSet();
 JsonObject jsonObject = new Gson().fromJson(response, JsonObject.class).getAsJsonObject();
 JsonArray array = jsonObject.getAsJsonArray("sobjects");
 for (JsonElement element : array) {
  String sourceEntityName = element.getAsJsonObject().get("name").getAsString();
  result.add(SourceEntity.fromSourceEntityName(sourceEntityName));
 }
 return result;
}

代码示例来源:origin: apache/pulsar

@Override
public void configure(String encodedAuthParamString) {
  JsonObject params = new Gson().fromJson(encodedAuthParamString, JsonObject.class);
  userId = params.get("userId").getAsString();
  password = params.get("password").getAsString();
}

代码示例来源:origin: chanjarster/weixin-java-tools

public WxMpMassNews deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
  WxMpMassNews wxMpMassNews = new WxMpMassNews();
  JsonObject json = jsonElement.getAsJsonObject();
  if (json.get("media_id") != null && !json.get("media_id").isJsonNull()) {
   JsonArray articles = json.getAsJsonArray("articles");
   for (JsonElement article1 : articles) {
    JsonObject articleInfo = article1.getAsJsonObject();
    WxMpMassNews.WxMpMassNewsArticle article = WxMpGsonBuilder.create().fromJson(articleInfo, WxMpMassNews.WxMpMassNewsArticle.class);
    wxMpMassNews.addArticle(article);
   }
  }
  return wxMpMassNews;
 }
}

代码示例来源:origin: immutables/immutables

@Test
public void otherAttributes() {
 String json = "{\"a\":1,\"b\":\"B\",\"c\":true,\"d\":null}";
 OtherAttributes o = gsonWithOptions.fromJson(json, OtherAttributes.class);
 check(o.rest().get("c")).is(new JsonPrimitive(true));
 check(o.rest().get("d")).is(JsonNull.INSTANCE);
 check(gsonWithOptions.toJson(o)).is(json);
}

代码示例来源:origin: chanjarster/weixin-java-tools

public WxMpMaterialNewsBatchGetResult.WxMaterialNewsBatchGetNewsItem deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
  WxMpMaterialNewsBatchGetResult.WxMaterialNewsBatchGetNewsItem wxMaterialNewsBatchGetNewsItem = new WxMpMaterialNewsBatchGetResult.WxMaterialNewsBatchGetNewsItem();
  JsonObject json = jsonElement.getAsJsonObject();
  if (json.get("media_id") != null && !json.get("media_id").isJsonNull()) {
   wxMaterialNewsBatchGetNewsItem.setMediaId(GsonHelper.getAsString(json.get("media_id")));
  }
  if (json.get("update_time") != null && !json.get("update_time").isJsonNull()) {
   wxMaterialNewsBatchGetNewsItem.setUpdateTime(new Date(1000 * GsonHelper.getAsLong(json.get("update_time"))));
  }
  if (json.get("content") != null && !json.get("content").isJsonNull()) {
   JsonObject newsItem = json.getAsJsonObject("content");
   wxMaterialNewsBatchGetNewsItem.setContent(WxMpGsonBuilder.create().fromJson(newsItem, WxMpMaterialNews.class));
  }
  return wxMaterialNewsBatchGetNewsItem;
 }
}

相关文章