java - JSON inner field parsing with GSON -
i new json , love how incredibly potent , straight-forward gson api can be, compared other parsing methods i've researched.
want parse rather complex json(using gson) resembles following 1 in terms of structure:
[ { "name": "steve", "age": 42, "description": null, "email1": "steve@example.com", "email2": null, "address1": { "type": "home", "shippingmethod": "charge quantity", "street": "sunrise ave", "streetno": 17 }, "address2": { "type": "office", "shippingmethod": null, "street": "sunset ave", "streetno": 71 }, "anotherfield": "another value" }, { "name": "johnny", ... "anotherfield": "some other value" } ]
i can see need wrap array of client objects, because json starts "[" , can see need container class inner fields address1 , address2. container came with:
public class client { string name; int age; string description; string email1; string email2; clientaddress address1; clientaddress address2; string anotherfield; .. getters() , setters() public class clientaddress { string type; string shippingmethod; string street; int streetno; .. getters() , setters() } }
the instruction wrote grab data , populate wrapper fields is:
client[] clientsarray= (new gson()).fromjson(jsonclients, client[].class);
the result partially satisfying; managed access primitive fields (such name,email1..), address1 , address2 fields both null. result,
clientsarray[i].getaddress1().getshippingmethod();
returns null string.
where did go wrong?
there particular way of creating classes missing?
note: json object valid structure standpoint of view. if see errors, it's because slipped when manually creating above dummy/demo.
just follow gson collections practices , try changing
client[] clientsarray= (new gson()).fromjson(jsonclients, client[].class);
to
type collectiontype = new typetoken<list<client>>(){}.gettype(); list<client> clientsarray = (new gson()).fromjson(jsonclients, collectiontype);
Comments
Post a Comment