java - Parsing complex nested JSON data with Gson -
i'm using gson parse json string. want convert object using container class , embedded static classes. extent has been possible, want treat content of stuff1
, stuff2
arrays, example, stuff1
array containing other_stuff1
, other_stuff2
. can reference object in fashion these: object.integer
, object.stuff1.get("other_stuff1").name
, or object.stuff2.get("other_stuff3").more
. (for last one, interested in looping on more
each item.
for example, in php, use this:
<?php echo "<pre>"; $object = json_decode(file_get_contents("the json filename")); foreach($object->stuff1 $name=>$data) { echo $name . ":\n"; // other_stuff1 or other_stuff2 echo $unlockable->description . "\n\n"; // got lots of stuff or got more stuff. } ?>
i want able reference in similar way, loading json object used on fly.
it crucial that, while degree of change can made json, names of elements remain , referable , retrievable.
i've included json, similar 1 i'm using, below.
{ "integer":"12345", "stuff1":{ "other_stuff1":{ "name":"a_name", "description":"got lots of stuff.", "boolean":false }, "other_stuff2":{ "name":"another_name", "description":"got more stuff", "boolean":true } }, "stuff2":{ "other_stuff3":{ "name":"a_name", "description":"got more stuff", "boolean":false, "more":{ "option1":{ "name":"hello" }, "option2":{ "name":"goodbye" } } }, } }
i've gone through number of reference guides , tutorials, , can't find way interpret way i'm trying to.
i'd appreciate if give me pointer. can't find tutorials take account a) want multiple objects in array-style list, referable ids (like other_stuff1
, other_stuff2
), , b) want able loop on items without providing ids.
you should define java class fields named after keys need. can use map
s (not arrays) .get("key")
behavior describe. example:
class container { private final int integer; private final hashmap<string, stuff> stuff1; private final hashmap<string, stuff> stuff2; } class stuff { private final string name; private final string description; @serializedname("boolean") private final boolean bool; private final hashmap<string, option> more; } class option { private final string name; }
for "boolean"
field need need use different variable name since boolean
reserved keyword.
you can do:
container c = gson.fromjson(jsonstring, container.class); for(stuff s : c.getstuff1().values()) { system.out.println(s.getname()); }
Comments
Post a Comment