【问题标题】:How can I keep the property used for setting the JsonSubTypes?如何保留用于设置 JsonSubTypes 的属性?
【发布时间】:2019-09-14 13:37:56
【问题描述】:

当使用 Jackson Datamapper 反序列化我的 yaml-config 时,配置中用于决定创建什么子类型的值会被忽略,而不是保存在创建的 java 对象中。

这是我正在尝试读取的配置...

#config
--- 
lists:
  - filename: filename.xlsx
    template: filename_template.xlsx
    type: classType #this value is ommitted
    ...

有了这个抽象类

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property="type")
@JsonSubTypes({
    @JsonSubTypes.Type(value = Example.class, name = "Example"),
    @JsonSubTypes.Type(value = OtherExample.class, name = "OtherExample")
})
public abstract class Report {

    private String filename;
    private String template;
    private String type; //this value is always null

    public Report() {

    }

并创建和调用 ObjectMapper:

ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
mapper.enableDefaultTyping();

String 类型应该是 JsonSubType 选项用来设置类型的值之一,而不是 null。

【问题讨论】:

    标签: java jackson yaml deserialization


    【解决方案1】:

    JsonTypeInfo 在内部由Jackson 处理。属性type 用于创建特定类,反序列化后不需要它,因为您有该类的实例。如果Jackson 实例化了Example 对象,你知道typeYaml 文件中被设置为Example。如果Jackson 实例化了OtherExample 对象,你知道typeYaml 文件中设置为OtherExample,等等...

    因此,您可以从Report 类中删除private String type;,并使用getClass().getSimpleName() 获取type

    【讨论】:

      【解决方案2】:

      与此同时,我通过在子类的构造函数中设置值类型来解决它。

      public OtherReport() {
              super();
              super.setReportType("OtherReport");
          }
      

      【讨论】:

        猜你喜欢
        • 2017-12-24
        • 2011-01-16
        • 1970-01-01
        • 1970-01-01
        • 2012-09-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多