Having a dynamic POJO like the next one:
@JsonInclude(JsonInclude.Include.NON_NULL)
public class MyDynamicWrapper <T> {
@JsonProperty("header")
private CommonHeader header;
@JsonProperty("payload")
private T payload;
public MyDynamicWrapper(CommonHeader header, T payload) {
super();
this.header = header;
this.payload = payload;
}
public CommonHeader getHeader() {
return header;
}
public void setHeader(CommonHeader header) {
this.header = header;
}
public T getPayload() {
return payload;
}
public void setPayload(T payload) {
this.payload = payload;
}
}
Where T
payload could be one of the following:
@JsonInclude(JsonInclude.Include.NON_NULL)
public class MyPayloadOne {
@JsonProperty("status")
private int status;
@JsonProperty("action")
private String action;
...
}
@JsonInclude(JsonInclude.Include.NON_NULL)
public class MyPayloadTwo {
@JsonProperty("properties")
private List<String> properties = new ArrayList<>();
...
}
What is the best way to deserialize this dynamic information with Jackson? Is it mandatory to implement a deserializer? My current configuration is not dynamic and I am using:
MyDynamicWrapper pojo = jacksonMapper.readValue(jsonMessage, MyDynamicWrapper.class);
I think this is so obvious but I do not know how to indicate the dynamic reference to Jackson.
Update
In addition to the accepted answer, I have checked that also is possible to define the jackson mapper like this:
MyDynamicWrapper<?> pojo = jacksonMapper.readValue(jsonMessage, MyDynamicWrapper.class);
This will transform the POJO to both payloads.