2

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.

2
  • 1
    Just create a custom deserializer that switches depending on the key. Commented Aug 10, 2016 at 14:17
  • @BoristheSpider No custom deserializers are required :) Commented Aug 10, 2016 at 15:43

1 Answer 1

13

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.