2013-07-23 23 views
0

我試圖從JSON中填充POJO,該方法並不以任何方式匹配,並且無法解決此問題。我無法更改JSON,因爲它是外部服務,但如果需要,我可以修改POJO。無法使用JSON使用Jackson填充POJO

下面是一個例子JSON:

{"Sparse":[{"PixId":1,"PixName":"SWE","Description":"Unknown"},{"PixId":2,"PixName":"PUMNW","Description":"Power Supplement"}],"Status":0,"Message":null} 

下面是POJO:

@JsonIgnoreProperties(ignoreUnknown = true) 
public class Pix { 
    @JsonProperty("Description") 
    private String description; 
    @JsonProperty("PixId") 
    private int pixId; 
    @JsonProperty("PixName") 
    private String pixName; 


    // getters and setters 
} 

這裏是我的代碼來進行轉換:

ObjectMapper om = new ObjectMapper(); 
om.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); 
om.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); 
List<Pix> pixList = om.readValue(pixJson, new TypeReference<List<Pix>>() {}); 

的pixList只包含1元素(應該是2使用上面的JSON),並且所有的屬性都沒有被填充。我使用傑克遜1.9.9。任何想法如何讓這個工作? TIA。

回答

0

您必須爲包含List<Pix>的主對象創建新的POJO類。它可能看起來像這樣:

class Root { 

    @JsonProperty("Status") 
    private int status; 

    @JsonProperty("Message") 
    private String message; 

    @JsonProperty("Sparse") 
    private List<Pix> sparse; 

    //getters/setters 
} 

現在你的反序列化的代碼可以是這樣的:

ObjectMapper mapper = new ObjectMapper(); 
mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); 
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); 

List<Pix> pixList = mapper.readValue(pixJson, Root.class).getSparse(); 
+0

雖然我討厭改變POJO,包括不必要的字段不相關,上述工作。希望忽略屬性以及強制類型引用會做到這一點。 –