Jackson 为一个具有多态类型的字段自定义反序列化程序
2022-09-01 13:26:10
更新:
我试图在jackson源代码中调试,并在方法中发现
deserialize(JsonParser jp, DeserializationContext ctxt)
之
SettableBeanProperty.java
当 不为空时,它永远不会使用 ._valueTypeDeserializer
_valueDeserializer
这是否是正确的假设,即类型解析器应该比值解析器更合适?
我正在尝试使用为具有多态类型的字段定义自定义反序列化程序。我可以成功地使用和分开。但是当我一起使用它们时,似乎注释被忽略了。@JsonDeserialize
@JsonDeserialize
@JsonTypeInfo
@JsonDeserialize
这是我的类层次结构:
1. 定义.java
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type", defaultImpl = Definition.class)
@JsonSubTypes({@Type(value = Definition.class, name = "normal"),
@Type(value = FormDefinition.class, name = "form")})
public class Definition {
private String name;
private String description;
// getter&setter for name&description
}
2. 表单定义.java
public class FormDefinition extends Definition {
private String formName;
@JsonDeserialize(using = DefinitionDeserializer.class)
private Definition definition;
public String getFormName() {
return formName;
}
public void setFormName(String formName) {
this.formName = formName;
}
public void setDefinition(Definition definition) {
this.definition = definition;
}
}
3. 定义析射器.java
public class DefinitionDeserializer extends JsonDeserializer<Definition> {
@Override
public Definition deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
throws IOException, JsonProcessingException {
Definition definition = new Definition();
String name = jsonParser.readValueAs(String.class);
definition.setName(name);
return definition;
}
}
样品主
public class App
{
public static void main( String[] args ) throws IOException {
String sampleData = "{\"type\":\"form\",\"definition\":\"super\",\"formName\":\"FormName\"}";
ObjectMapper mapper = new ObjectMapper();
Definition definition = mapper.readValue(sampleData, Definition.class);
System.out.println(definition);
}
}
运行示例主应用将引发异常:
Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: Can not instantiate value of type [simple type, class jp.co.worksap.model.Definition] from String value ('super'); no single-String constructor/factory method (through reference chain: jp.co.worksap.model.FormDefinition["definition"])
这似乎用于反序列化类的字段,而不是带注释的反序列化程序。AsPropertyTypeDeserializer
definition
FormDefinition
DefinitionDeserializer
我认为这里棘手的部分是,我想使用自定义解串器的领域也是用于解决多态问题的类型。Definition
@JsonTypeInfo
有没有办法一起使用它们?谢谢。