简体   繁体   English

JSON解析到多个POJO集合

[英]JSON parsing to multiple POJOs collection

I need to somehow convert a single json string into multiple objects of a particular type using GSON. 我需要使用GSON以某种方式将单个json字符串转换为特定类型的多个对象。

I have the format of a single json string (below contains 2 but there may be 100s) 我有一个json字符串的格式(下面包含2,但可能有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. 现在,我想将以上内容转换为映射到字符串各部分的pojo实例。 Suppose the POJO is called Website. 假设POJO称为网站。 Then I need to split up the json string to 2 Website objects. 然后,我需要将json字符串拆分为2个Website对象。

I was thinking of splitting the json string using a tokenizer of some sort and then applying some json logic on each part. 我正在考虑使用某种标记器拆分json字符串,然后在每个部分上应用一些json逻辑。 I'm assuming I would have to do this before applying any json to pojo conversion? 我假设我必须在将任何json应用于pojo转换之前必须执行此操作?

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/ . 要将json反序列化为Java pojo,请尝试json-lib, http://json-lib.sourceforge.net/ This is a good solution. 这是一个很好的解决方案。 Although I would use flexjson for serialization. 虽然我会使用flexjson进行序列化。

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. BeanA是您的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: 首先将您的字符串固定为有效的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: 然后使用标准gson技术转换为网站列表:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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