当使用 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。
最佳答案
JsonTypeInfo
由 Jackson
在内部处理。属性type
用于创建特定的类,反序列化后您不需要它,因为您有该类的实例。如果 Jackson
实例化了 Example
对象,您就知道 type
在 Yaml
文件中设置为 Example
。如果 Jackson
实例化了 OtherExample
对象,您知道 type
在 Yaml
文件中设置为 OtherExample
等...
因此,您可以从 Report
类中删除 private String type;
并使用 getClass().getSimpleName()
获取 type
。
关于java - 如何保留用于设置 JsonSubTypes 的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57936040/