简体   繁体   中英

How to define 2-level inheritance structure with Jackson

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, ie define all the subtypes at the Message annotation level?

Thanks!

It seems that this is not supported. Look at this issue: https://github.com/FasterXML/jackson-databind/issues/374

The last answer:

It is not supported and there are no plans to support it. Do not design your system assuming this will be implemented.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM