java - Parse JSON file using GSON -
i want parse json file in java using gson :
{ "descriptor" : { "app1" : { "name" : "mehdi", "age" : 21, "messages": ["msg 1","msg 2","msg 3"] }, "app2" : { "name" : "mkyong", "age" : 29, "messages": ["msg 11","msg 22","msg 33"] }, "app3" : { "name" : "amine", "age" : 23, "messages": ["msg 111","msg 222","msg 333"] } } }
but don't know how acceed root element : descriptor, after app3 element , name element.
i followed tutorial http://www.mkyong.com/java/gson-streaming-to-read-and-write-json/, doesn't show case of having root , childs elements.
imo, best way parse json response gson creating classes "match" response , use gson.fromjson()
method.
example:
class response { map<string, app> descriptor; // standard getters & setters... } class app { string name; int age; string[] messages; // standard getters & setters... }
then use:
gson gson = new gson(); response response = gson.fromjson(yourjson, response.class);
where yourjson
can string
, reader
, jsonreader
or jsonelement
.
finally, if want access particular field, have do:
string name = response.getdescriptor().get("app3").getname();
you can parse json manually suggested in other answers, think approach clearer, more maintainable in long term , fits better whole idea of json.
Comments
Post a Comment