I need to somehow convert a single json string into multiple objects of a particular type using GSON.
I have the format of a single json string (below contains 2 but there may be 100s)
{domain : name1, geo: us} {domain : name2, country : uk}
Now I want to convert the above into my pojo instances that map to each part of the string. Suppose the POJO is called Website. Then I need to split up the json string to 2 Website objects.
I was thinking of splitting the json string using a tokenizer of some sort and then applying some json logic on each part. I'm assuming I would have to do this before applying any json to pojo conversion?
I cant seem to find a way to do this. Please advise.
thanks so much
To deserialize json to a java pojo, try json-lib, http://json-lib.sourceforge.net/. This is a good solution. Although I would use flexjson for serialization.
String json = "{bool:true,integer:1,string:\"json\"}";
JSONObject jsonObject = JSONObject.fromObject( json );
BeanA bean = (BeanA) JSONObject.toBean( jsonObject, BeanA.class );
where BeanA is your POJO.
If you have muliple objects, like you showed in your example then do the following
String json = "{'data':[{'name':'Wallace'},{'name':'Grommit'}]}";
JSONArray jsonArray = (JSONArray) net.sf.json.JSONSerializer.toJSON(json);
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
BeanA bean = (BeanA) JSONObject.toBean( jsonObject, BeanA.class );
//do whatever you want with each object
}