Abhijith Madhav Abhijith Madhav - 2 months ago 10x
JSON Question

How to deserialize a json array containing different types of objects

Here is a json snippet which contains an array(icons) which can contain two different types of objects(application and folder)

"icons": [{
"application": {
"displayName": "Facebook",
"bundleId": "com.facebook.com"
}, {
"folder": {
"some": "value",
"num": 3

How can I create java POJO's modelling this kind of json and then deserialize the same?

I referred to this question. But I can't change the json I'm getting to include a 'type' as advised there and then use inheritance for the POJO's of the two different objects.


No custom deserializers are required. A smart @JsonTypeInfo will do the trick.

See below what the classes and interfaces can be like:

@JsonTypeInfo(use = Id.NAME, include = As.WRAPPER_OBJECT)
@JsonSubTypes({ @Type(value = ApplicationIcon.class, name = "application"),
                @Type(value = FolderIcon.class, name = "folder") })
public interface Icon {

public class ApplicationIcon implements Icon {

    public String displayName;
    public String bundleId;

    // Getters and setters ommited
public class FolderIcon implements Icon {

    public String some;
    public Integer num;

    // Getters and setters ommited
public class IconWrapper {

    private List<Icon> icons;

    // Getters and setters ommited

To deserialize your JSON, do as following:

String json = "{\"icons\":[{\"application\":{\"displayName\":\"Facebook\",\"bundleId\":\"com.facebook.com\"}},{\"folder\":{\"some\":\"value\",\"num\":3}}]}";

ObjectMapper mapper = new ObjectMapper();
IconWrapper iconWrapper = mapper.readValue(json, IconWrapper.class);