用Jackson Java解析JSON [英] Parsing JSON with Jackson Java
本文介绍了用Jackson Java解析JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在用Jackson解析JSON时遇到问题.我有一个 POJO 对象,该对象被另一个包裹.
I have a problem while parsing JSON with Jackson. I have a POJO object, wrapped by another.
这是我的代码:
in main:
ObjectMapper mapper = new ObjectMapper();
List<ItemBean> mpl2 = mapper.readValue(col.toString(),new TypeReference<List<ItemBean>>() {});
my POJO class:
public class ItemBean implements Serializable {
private List<Item> items;
@JsonProperty("Item")
public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
}
public class Item implements Serializable{
public String field1;
public Integer field2;
public static final class Field3 extends GenericJson {
private String subfield1;
private String subfield2;
}
}
这是引发的异常:
org.codehaus.jackson.map.exc.UnrecognizedPropertyException: Unrecognized field "item" (Class bean.item), not marked as ignorable
at [Source: java.io.StringReader@101b6d56; line: 4, column: 16] (through reference chain: bean.ItemBean["items"]->bean.Item["item"])
JSON的显示方式如下:
JSON looks in a such way:
["{\n
\"items\":
[
\n {
\n \"item\": {
\n \"field1\": \"val1\",
\n \"field2\": \"val2\",
\n \"field3\": [
\n {
\n \"subfield1\": subval
\n \"subfield2\": subval
\n }
\n ]
\n }
\n },
\n \"item\": {
\n \"field1\": \"val1\",
\n \"field2\": \"val2\",
\n \"field3\": [
\n {
\n \"subfield1\": subval
\n \"subfield2\": subval
\n }
\n ]
\n }
\n },
\n \"item\": {
\n \"field1\": \"val1\",
\n \"field2\": \"val2\",
\n \"field3\": [
\n {
\n \"subfield1\": subval
\n \"subfield2\": subval
\n }
\n ]
\n }
\n },
etc...... may I haven't closed brackets correctly, but they are correct :)
}
]
"]
POJO完全重复JSON对象的字段.
POJO totally repeat the fields of the JSON object.
推荐答案
我编写了自己的方法,该方法解析这种结构的JSON.
I wrote my own method, which parses JSON of such a structure.
这是代码:
public static List parseList(String jsonInput, Class clazz) {
List result = new LinkedList();
JSONArray json = (JSONArray) JSONSerializer.toJSON(jsonInput);
JSONObject items = (JSONObject)json.getJSONObject(0);
JSONArray dataArrayJSON = (JSONArray)items.getJSONArray("items");
for (int i = 0; i < dataArrayJSON.size(); i++) {
result.add(JSONObject.toBean(dataArrayJSON.getJSONObject(i).getJSONObject("item"), clazz));
}
return result;
}
问题在于项目位于数组中,而项目是唯一的元素.项目本身也是一个数组,因此我使用了dataArrayJSON.getJSONObject(i).getJSONObject("item")
构造.
The problem was that items are in the array and items is the only element. items in its turn, is also an array, thus I used the dataArrayJSON.getJSONObject(i).getJSONObject("item")
construction.
这篇关于用Jackson Java解析JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文