用Jackson Java解析JSON

我在与jackson解析JSON时遇到了问题。 我有一个POJO对象,由另一个包裹。

这是我的代码:

in main: ObjectMapper mapper = new ObjectMapper(); List mpl2 = mapper.readValue(col.toString(),new TypeReference<List>() {}); my POJO class: public class ItemBean implements Serializable { private List items; @JsonProperty("Item") public List getItems() { return items; } public void setItems(List 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; } } 

这是抛出的exception:

 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看起来像这样:

 ["{\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对象的字段。

我编写了自己的方法,解析了这种结构的JSON。

这是代码:

 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")构造。