java - Deserializing JSON with Gson -


i server response complex objects build in following way:

json array of object type            { jsonobject json array of object type b                  } 

i'm trying deserialize object typea , object typeb ones in below example:

public class objecta{    string a;    int b;    arraylist<objectb> list; }  public class objectb{    string a1;    int b2;    string c3; } 

this example of json

[    {       "a": "a",       "b": 1,       "list": [          {             "a1": "a1",             "b2": 2,             "c3": "c3"          },          {             "a1": "a1",             "b2": 2,             "c3": "c3"          }       ]    },    {       "a": "a",       "b": 1,       "list": [          {             "a1": "a1",             "b2": 2,             "c3": "c3"          },          {             "a1": "a1",             "b2": 2,             "c3": "c3"          }       ]    } ] 

how deserialize this?

since have class hierarchy, can take advantage of , let gson work you. explain better mean, prepared code ready run:

package stackoverflow.questions.q18123430;  import java.lang.reflect.type; import java.util.*;  import com.google.gson.gson; import com.google.gson.reflect.typetoken;  public class q18123430 {      public static class objecta {         string a;         int b;         arraylist<objectb> list;          @override         public string tostring() {             return "objecta [a=" + + ", b=" + b + ", list=" + list + "]";         }      }      public static class objectb {         string a1;         int b2;         string c3;          @override         public string tostring() {             return "objectb [a1=" + a1 + ", b2=" + b2 + ", c3=" + c3 + "]";         }      }      public static void main(string[] args) {         string json = "[{  a:\"a\",b:1,list:  [{a1:\"a1\",b2:2,c3:\"c3\"},{a1:\"a1\",b2:2,c3:\"c3\"}]}, {  a:\"a\",b:1,list:  [{a1:\"a1\",b2:2,c3:\"c3\"},{a1:\"a1\",b2:2,c3:\"c3\"}]}]";         type listofobjecta = new typetoken<list<objecta>>() {         }.gettype();          gson g = new gson();         arraylist<objecta> result = g.fromjson(json, listofobjecta);         system.out.println(result);      }  } 

and execution result:

[objecta [a=a, b=1, list=[objectb [a1=a1, b2=2, c3=c3], objectb [a1=a1, b2=2, c3=c3]]], objecta [a=a, b=1, list=[objectb [a1=a1, b2=2, c3=c3], objectb [a1=a1, b2=2, c3=c3]]]] 

Comments

Popular posts from this blog

matlab - Deleting rows with specific rules -

jquery - How would i go about shortening this code? And to cancel the previous click on click of new section? -