java - 如何用 Jackson 定义 2 级继承结构

标签 java json jackson

我有以下基本(接口(interface))结构

@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();
}
AppMessage类是一个简单的 POJO(现在),比如
public class AppMessage implements Message {

    private String appId; 
    ...
    private Date timestamp = Date.from(Instant.now());

}

但是 NotificationMessage是另一个界面

@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();
}

当然还有两个 pojo 为 NotificationAckMessageNotificationReqMessage实现 NotificationMessage 的类.

每当我想反序列化 NotificationMessage

{"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);

我明白了

Can not construct instance of NotificationMessage: abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information



当然是 AppMessage得到解析没有任何错误。

如何在不展平的情况下实现这种结构和逻辑,即在 Message 处定义所有子类型注释级别?

谢谢!

最佳答案

似乎不支持此功能。看这个问题:https://github.com/FasterXML/jackson-databind/issues/374

最后一个答案:

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

关于java - 如何用 Jackson 定义 2 级继承结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60697181/

相关文章:

Java 正则表达式不起作用,相同的模式适用于在线网站

javascript - 在 PHP 中,我从 mySQL 编码了一个 JSON 数组。我想在不同的 php 文件中解码它

java - json 到 java 对象自定义解析器

ios - 你如何在swift中解析json?

java - 如何使用 Jackson 反序列化混合类型的匿名数组

java - 无法从 START_ARRAY token 中反序列化对象的实例

java - 可以配置 Jackson-Json Mapper 以根据它正在序列化的对象排除属性吗?

java - 我如何在 couchdb 中使用 OR 大小写查询

java - 传递 Maven 依赖项出现在依赖项 :tree but not in lib directory 中

java - 消除计算字段上的 LazyInitializationException 的最佳方法是什么?