2012-07-05 106 views
1

解析JSON與傑克遜時出現問題。我有一個POJO對象,由另一個包裹。與傑克遜Java解析JSON

這裏是我的代碼:

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: [email protected]; 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對象。

+0

JSON的外觀如何? – Thomas 2012-07-05 14:42:32

+0

@Thomas補充了json – 2012-07-05 14:55:11

回答

1

我寫了我自己的方法,它解析了這種結構的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")構造。