2

I have the following Json:

{
    "id": "id1",
    "version": "id1",
    "license": { "type": "MIT" }
}

Which can also be in the form of:

{
    "id": "id1",
    "version": "id1",
    "license": "MIT"
}

And sometimes it can be:

{
    "id": "id1",
    "version": "id1",
    "licenses": [
    { "type": "MIT", "url: "path/to/mit" },
    { "type": "Apache2", "url: "path/to/apache" }]
}

All of the above are essentially the same, I'm looking for a way to combine them with a single field and deserialize it using Jackson. Any Ideas?

shayy
  • 1,272
  • 2
  • 16
  • 26

1 Answers1

3

At the beginning, please, see this this question: Jackson deserialization of type with different objects. You can deserialize your JSON to below POJO class:

class Entity {

    private String id;
    private String version;
    private JsonNode license;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }

    public JsonNode getLicense() {
        return license;
    }

    public void setLicense(JsonNode license) {
        this.license = license;
    }

    public void setLicenses(JsonNode license) {
        this.license = license;
    }

    public String retrieveLicense() {
        if (license.isArray()) {
            return license.elements().next().path("type").asText();
        } else if (license.isObject()) {
            return license.path("type").asText();
        } else {
            return license.asText();
        }
    }

    @Override
    public String toString() {
        return "Entity [id=" + id + ", version=" + version + ", license=" + license + "]";
    }
}

Use retrieveLicense method if you want to retrieve licence name from the POJO class. Of course, you can improve implementation of this method. My example shows only the way how you can implement it. If you want to decouple POJO class from deserialization logic you can write custom deserializer.

Community
  • 1
  • 1
Michał Ziober
  • 37,175
  • 18
  • 99
  • 146
  • Thanks, I'll use this method before going to custom deserializers. – shayy Dec 02 '13 at 07:35
  • 1
    In addition: note that you can have separate setters for "license" and "licenses", even if logically they refer to same property. They would then take different arguments; and you may still internally use just a single field if you want. As long as you have getter and setter, internal field is of no interest to Jackson (is ignored). – StaxMan Dec 04 '13 at 21:05