I have a POJO which is used for mapping the values received from rabbitmq. The messages are sent from other third-party services which I don't have control over. The problem is that these services don't send the certain fields in a consistent manner.
For example, in the case of an error
field, this field will only have information when the third-party service wants to send a message to inform that there is an error. Some services may send in their JSON message to the queue this way:
{
id: 123,
name: "PersonA",
error: null
}
And then there are also services that may send their JSON message this way:
{
id: 123,
name: "PersonA",
error: []
}
And there are also services that may just omit the field entirely:
{
id: 123,
name: "PersonA"
}
Of course, if there is an error, that error field will contain fields within it:
{
id: 123,
name: "PersonA",
error: {
message: "Cannot find PersonA"
}
}
So, there is a chance that the error field can be null
, undefined
, array
or an object
.
The problem is, I can only define a single type in my POJO for the error
field.
public class MyMessage {
private int id;
private MessageError error;
private String name;
@JsonCreator
public MyMessage(
@JsonProperty("id") int id,
@JsonProperty("error") MessageError error, // error is a MessageError object already but what is sent in could be null, undefined, an array or an object
@JsonProperty("name") String name
) {
this.id = id;
this.error = error;
this.name = name;
}
}
public class MessageError {
private String message;
@JsonCreator
public MessageError(
@JsonProperty("message") String message
) {
this.message = message;
}
}
I'm using Spring with Jackson.
In this case, how can I handle and map all the possible values that maybe assigned to the error
field in the message to the POJO when it gets deserialised?