0

I'm trying to populate a POJO from a JSON that doesn't really match in any way and am having trouble getting this resolved. I can't change the JSON since it is an external service but I maybe able to modify the POJO if needed.

Below is an example JSON:

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

Below is the 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
}

And here is my code to do the conversion:

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>>() {});

The pixList contains only 1 element (should be 2 using the JSON above) and all the properties have not been populated. I'm using Jackson 1.9.9. Any ideas on how to get this to work? TIA.

4

1 回答 1

0

You have to create new POJO class for main object which contains the List<Pix>. It could looks like this:

class Root {

    @JsonProperty("Status")
    private int status;

    @JsonProperty("Message")
    private String message;

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

    //getters/setters
}

And now your deserialization code could looks like this:

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();
于 2013-07-24T07:09:28.170 回答