java - Parsing dynamic JSON data with Gson -
i'm beginner java , gson user , have been able apply needs. have json data need parse spinner follows:
{ "lang":[ "arabic", "bengali", "dutch-utf8", "eng_root", "english", "english-utf8", ... ], "themes":{ "blue":{ "chinese_ibm500":1, "spanish":1, "bengali":1, "japanese":1, "english":1, "russian":1, "french-utf8":1, "eng_root":1, "arabic":1, "spanish-utf8":1, "portuguese":1, ... }, "green":{ "eng_root":1, "engmonsoon":1, "english":1 ... }, "red":{ "chinese_ibm500":1, "spanish":1, "bengali":1, ... } } }
so json need 2 things:
1) array under lang dynamic languages installed on server. how entries?
i have class follows im stuck should after return lang
public class listdata { private list<language> lang; public list<language> getlang { return lang; } public static class language { ??? } }
2) after understanding 1 might able figure 1 out. under themes colors again can more or less {purple, orange, whatever}. need list of themes, far i'm concerned don't need know languages each.
feel question turning book. have searched extensively , hate asking questions i'm pretty stumped. in advance.
1) in order "lang"
array, modify
private list<language> lang;
for
private list<string> lang;
since elements inside "lang"
array strings, don't need class language
store values, they'll parsed correctly strings. , doesn't matter how many strings array contains...
2) in order parse "themes"
, have notice it's not array [ ]
, object { }
, need parse object, , suitable class here map
this:
private map<string, object> themes;
note: said don't need data under "blue"
, "green"
, etc... can object
value type in map, otherwise you'd need class...
using map
here allows have arbitrary number of themes in json response.
so in summary, need class like:
public class listdata { private list<string> lang; private map<string, object> themes; //getters & setters }
and parse json with:
gson gson = new gson(); listdata data = gson.fromjson(yourjsonstring, listdata.class);
your list of langs under:
data.getlang();
and list of themes under:
data.getthemes().keyset();
i suggest take @ gson documentation. it's quite short , clear , you'll understand better...
Comments
Post a Comment