shayy
shayy

Reputation: 1312

How to deserialize dynamic field using Jackson?

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?

Upvotes: 2

Views: 2861

Answers (1)

Michał Ziober
Michał Ziober

Reputation: 38690

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.

Upvotes: 3

Related Questions