Tabnine Logo
Gson.fromJson
Code IndexAdd Tabnine to your IDE (free)

How to use
fromJson
method
in
com.google.gson.Gson

Parsing JSON documents to java classes using gson

Refine searchRefine arrow

  • Gson.<init>
  • GsonBuilder.<init>
  • PrintStream.println
  • GsonBuilder.create
  • JsonElement.getAsJsonObject
  • JsonObject.get
  • Gson.toJson
  • JsonParser.parse
  • JsonParser.<init>
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;
 }
}
com.google.gsonGsonfromJson

Javadoc

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).

Popular methods of Gson

  • toJson
    This method serializes the specified object, including those of generic types, into its equivalent J
  • <init>
  • toJsonTree
    This method serializes the specified object, including those of generic types, into its equivalent r
  • getAdapter
    Returns the type adapter for type.
  • getDelegateAdapter
    This method is used to get an alternate type adapter for the specified type. This is used to access
  • newJsonWriter
    Returns a new JSON writer configured for this GSON and with the non-execute prefix if that is config
  • newJsonReader
    Returns a new JSON reader configured for the settings on this Gson instance.
  • assertFullConsumption
  • doubleAdapter
  • floatAdapter
  • longAdapter
  • fieldNamingStrategy
  • longAdapter,
  • fieldNamingStrategy,
  • toString,
  • atomicLongAdapter,
  • atomicLongArrayAdapter,
  • checkValidFloatingPoint,
  • excluder,
  • newBuilder,
  • fromGson

Popular in Java

  • Reactive rest calls using spring rest template
  • findViewById (Activity)
  • scheduleAtFixedRate (Timer)
  • requestLocationUpdates (LocationManager)
  • FileInputStream (java.io)
    An input stream that reads bytes from a file. File file = ...finally if (in != null) in.clos
  • Thread (java.lang)
    A thread is a thread of execution in a program. The Java Virtual Machine allows an application to ha
  • ServerSocket (java.net)
    This class represents a server-side socket that waits for incoming client connections. A ServerSocke
  • SimpleDateFormat (java.text)
    Formats and parses dates in a locale-sensitive manner. Formatting turns a Date into a String, and pa
  • Logger (org.apache.log4j)
    This is the central class in the log4j package. Most logging operations, except configuration, are d
  • Scheduler (org.quartz)
    This is the main interface of a Quartz Scheduler. A Scheduler maintains a registry of org.quartz.Job
  • Best plugins for Eclipse
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now