java - Different JSON array response -


i have problems parsing 2 different json responses.

1: json response restful api:

{   "gear": [     {       "idgear": "1",       "name": "nosilec za kolesa",       "year": "2005",       "price": "777.0"     }, {       "idgear": "2",       "name": "stresni nosilci",       "year": "1983",       "price": "40.0"     }   ] } 

2: response testing client. added values list , used gson.tojson testing output.

[   {     "idgear": "1",     "name": "lala",     "year": 2000,     "price": 15.0   }, {     "idgear": "2",     "name": "lala2",     "year": 2000,     "price": 125.0   } ] 

they both valid, second 1 deserialize object this:

type listtype = new typetoken<list<gear>>() {}.gettype(); list<gear> gears= (list<gear>) gson.fromjson(json, listtype);  

with first one, trying deserialize same way error.


edit

api method:

@get @produces(mediatype.application_json) public list<gear> getgear() {   list<gear> gears = geardao.getgears();   if (!gears.isempty()) {     return gears;   } else     throw new runtimeexception("no gears"); } 

client serialization code:

list<gear> list = new arraylist<gear>(); gear o = new gear(); o.setprice(15); o.setyear(2000); o.setname("asds"); type listtypes = new typetoken<list<gear>>() {}.gettype(); gson.tojson(list, listtypes); 

the json responses different!

  • the first 1 object, surrounded { }, contains field "gear" in turn list of objects, surrounded [ ].

  • the second 1 directly list of objects, because it's surrounded [ ]. namely, whole 2nd response equivalent field in 1st response.

so, can't parsed in same way...

the 2nd 1 being parsed correctly because using list , list. 1st 1 need class contains field contains in turn list... is, need create class structure represents json responses...

public class response {         private list<gear> gears;             //getters & setters } 

now can parse 1st response with:

gson gson = new gson(); response response = gson.fromjson(json, response .class); list<gear> gears = response.getgears(); 

i suggest take brief @ json.org in order understand json syntax, pretty simple... these possible json elements:

object     {}     { members }  members     pair     pair , members pair     string : value array     []     [ elements ] elements     value     value , elements value     string     number     object     array     true     false     null  

Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -