简体   繁体   中英

JSON parsing to multiple POJOs collection

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
}

Assuming you have a class Website like this:

class Website {
    String domain;
    String geo;
}

First fix your string to be valid json:

String input = "{\"domain\" : \"name1\", \"geo\": \"us\"} {\"domain\" : \"name2\", \"country\" : \"uk\"}";

String json = "[" + input + "]";

Then use standard gson technique to convert to List of Website:

java.lang.reflect.Type t = new TypeToken<List<Website>>(){}.getType();
List<Website> websites = new Gson().fromJson(json, t);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM