无法使用Jackson在JSON中填充POJO

时间:2013-07-23 21:44:43

标签: jackson

我正在尝试从JSON中填充一个POJO,它不会以任何方式真正匹配并且无法解决问题。我无法更改JSON,因为它是一个外部服务,但我可以根据需要修改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个元素(使用上面的JSON应该是2个)并且尚未填充所有属性。我正在使用Jackson 1.9.9。有关如何使其工作的任何想法? TIA。

1 个答案:

答案 0 :(得分: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();