Thursday, April 26, 2012

Notes on Gson (when converting a Json string to a Java Object)


Google's Gson library provides a handy way to convert Java Class from/to Json strings using fromJson() and toJson() function.

When converting a Json string to Java object, it is important that the fields' names in the Java Class must be exactly the same as the keys' names in the Json String. The visibility of the fields' name does not matter. E.g.:

  String json = "{'key1':'1', 'key2':2}";
  class Object {
   public String key1;
   private int key2;
  }
  Object objs = new Gson().fromJson(json, Object.class);


Otherwise, the null values will returned for each field.

No comments:

Post a Comment

(Coding && Eating) || Sleeping