gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 10:24:11 25 4
gpt4 key购买 nike

我有以下基本(接口(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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com