Abhijith Madhav
Abhijith Madhav

Reputation: 2818

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.

Upvotes: 2

Views: 4389

Answers (1)

cassiomolin
cassiomolin

Reputation: 130917

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 {

}
@JsonRootName("application")
public class ApplicationIcon implements Icon {

    public String displayName;
    public String bundleId;

    // Getters and setters ommited
}
@JsonRootName("folder")
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);

Upvotes: 13

Related Questions