2

I am using spring restTemplate to map a response to a POJO. The response of the rest api is like this:

"attributes": { "name": { "type": "String", "value": ["John Doe"] }, "permanentResidence": { "type": "Boolean", "value": [true] }, "assignments": { "type": "Grid", "value": [{ "id": "AIS002", "startDate": "12012016", "endDate": "23112016" },{ "id": "AIS097", "startDate": "12042017", "endDate": "23092017" }] } } 

in the parent class, I have:

public class Users { private Map<String, Attribute> attributes; } 

If all the values of were String type, then I could have done like:

public class Attribute { private String type; private String[] value; } 

But the values are of different types. So I thought of doing the following:

public class Attribute { private String type; private Object[] value; } 

The above should work, but at every step I have to find out what is the type of Object.
So, my question is can I have something like this:

public class Attribute { @JsonProperty("type") private String type; @JsonProperty("value") private String[] stringValues; @JsonProperty("value") private Boolean[] booleanValues; @JsonProperty("value") private Assignments[] assignmentValues; // for Grid type } 

But it is not working and throwing errors: Conflicting setter definitions for property "value"

What is the recommended way of handling this scenario?

1 Answer 1

1

I would recommend Jackson facilities for handling polymorphism here:

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY, property = "type") @JsonSubTypes({ @JsonSubTypes.Type(value = BooleanAttribute.class, name = "Boolean"), @JsonSubTypes.Type(value = StringAttribute.class, name = "String") }) class Attribute { private String type; } class BooleanAttribute extends Attribute { private Boolean[] value; } class StringAttribute extends Attribute { private String[] value; } 

JsonTypeInfo tells Jackson that this is a base class and the type will be determined by a JSON field named "type"

JsonSubTypes maps subtypes of Attribute to values of "type" in JSON.

If you add an appropriate subtype for Assignments and getters/setters Jackson will be able to parse your JSON.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.