java - 将多态 json 序列化为特定的 jsonnode

标签 java json spring jackson

我有抽象类的列表

List<Messaging> data;

Messaging 是一个抽象类,另外 3 个类扩展了这个类。

例如,

   Message class extends Messaging
   Product class extends Messaging
   Filter class extends Messaging

我正在添加上面列表中的所有消息

我在 Messaging 类上使用了 @JsonTypeInfo,如下所示:

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY)
@JsonSubTypes({  
    @Type(value = Message.class, name = "message"),  
    @Type(value = Filter.class, name = "filter"),
    @Type(value = Product.class , name = "product")})

当我使用 jackson 将此 Java 对象序列化为 JSON 时,我得到如下值:

   {
        "@type": "message",
        "type": "text",
        "value": "Is this the information you need"
    }

我希望我的值(value)如下:

"message" : {
        "type": "text",
        "value": "Is this the information you need"
}

如何将多态对象列表序列化到不同的节点?

最佳答案

更改 JsonTypeInfo 以包含为 WRAPPER_OBJECT

例如:

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include=As.WRAPPER_OBJECT)

关于java - 将多态 json 序列化为特定的 jsonnode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45833715/

相关文章:

python - 在转换为 JSON 时在列表中附加元素

java - 如何动态确定运行时使用的服务类

java - Android:指定时间后停止AnimationDrawable,恢复onResume(),暂停onPause()

java - 拆分字符串不起作用。 (未使用局部变量的值)

java - Java 中的随机测试 - 它是什么以及如何实现它?

spring - 关于设计的问题,从另一个服务调用服务?

java - Swagger-ui 与 Spring 安全性

Java 与分页

c# - 在 C# 中从 Bing Map API 解析 JSON 代码

javascript - 查找 JSON 的最大值并存储为变量