I have the following base (interface) structure
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
property = "messageType",
visible = true)
@JsonSubTypes({
@JsonSubTypes.Type(value = AppMessage.class, name = "APP"),
@JsonSubTypes.Type(value = NotificationMessage.class, name = "NOTIFICATION"),
})
public interface Message {
MessageType getMessageType();
Date getTimestamp();
}
the AppMessage class is a simple POJO (for now) like
public class AppMessage implements Message {
private String appId;
...
private Date timestamp = Date.from(Instant.now());
}
but the NotificationMessage is another interface
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
property = "NotificationType",
visible = true)
@JsonSubTypes({
@JsonSubTypes.Type(value = NotificationAckMessage.class, name = "ACK"),
@JsonSubTypes.Type(value = NotificationReqMessage.class, name = "REQ"),
})
public interface NotificationMessage extends Message {
String getDest();
String getMessage();
MessageType getMessageType();
NotificationType getNotificationType();
}
and of course two more pojos as NotificationAckMessage and NotificationReqMessage classes which implements NotificationMessage.
When ever I want to deserialize NotificationMessage like
{"NotificationType": "REQ", "dest": "some dest", "message": "some message", "messageType": "NOTIFICATION", "notificationType": "REQ", "timestamp": 1584299876847}
ObjectMapper objectMapper = new ObjectMapper();
Message msg = objectMapper.readValue(msgStr, Message.class);
I get
Can not construct instance of NotificationMessage: abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information
of course the AppMessage getting parsed without any errors.
How can I achieve this kind of structure and logic without flatten it, i.e define all the subtypes at the Message annotation level?
Thanks!