【问题标题】:serialise polymorphic json to specific jsonnode将多态 json 序列化为特定的 jsonnode
【发布时间】:2017-08-23 07:48:49
【问题描述】:

我有抽象类的列表

List<Messaging> data;

Messaging 是一个抽象类,其他 3 个类正在扩展这个类。

例如,

   Message class extends Messaging
   Product class extends Messaging
   Filter class extends 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"
    }

我希望我的价值如下:

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

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

【问题讨论】:

    标签: java json spring jackson


    【解决方案1】:

    JsonTypeInfo 更改为WRAPPER_OBJECT

    例如:

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

    【讨论】:

      猜你喜欢
      • 2021-11-09
      • 1970-01-01
      • 1970-01-01
      • 2020-12-02
      • 1970-01-01
      • 1970-01-01
      • 2020-10-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多