Java Jackson:继承和必需属性
我目前正在尝试使用jackson实现一个反序列化程序,该程序能够处理多态性,也就是说,给定以下两个类:Java Jackson:继承和必需属性,java,json,jackson,polymorphism,jackson2,Java,Json,Jackson,Polymorphism,Jackson2,我目前正在尝试使用jackson实现一个反序列化程序,该程序能够处理多态性,也就是说,给定以下两个类: public abstract class Animal { private String name; private float weight; @JsonCreator protected Animal(@JsonProperty(value="name") String name, @JsonProperty(value="weight",required=true)
public abstract class Animal {
private String name;
private float weight;
@JsonCreator
protected Animal(@JsonProperty(value="name") String name, @JsonProperty(value="weight",required=true) int weight) {
this.name=name;
this.weight=weight;
}
}
public class Dog extends Animal {
private int barkVolume;
@JsonCreator
public Dog(String name,int weight, @JsonProperty(value="barkVolume",required=true) int barkVolume) {
super(name, weight);
this.barkVolume=barkVolume;
}
}
反序列化程序应该能够从json字符串推断并实例化适当的子类
我使用一个自定义的反序列化器模块,UniquePropertyPolymorphicDeserializer(来自)。该模块配置如下:
UniquePropertyPolymorphicDeserializer<Animal> deserializer =
new UniquePropertyPolymorphicDeserializer<Animal>(Animal.class);
deserializer.register("barkVolume", Dog.class);
SimpleModule module = new SimpleModule("UniquePropertyPolymorphicDeserializer");
module.addDeserializer(Animal.class, deserializer);
mapper.registerModule(module);
否则,反序列化程序将生成错误:
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Invalid type definition for type `Animals.Dog`: Argument #0 has no property name, is not Injectable: can not use as Creator [constructor for Animals.Dog, annotations: {interface com.fasterxml.jackson.annotation.JsonCreator=@com.fasterxml.jackson.annotation.JsonCreator(mode=DEFAULT)}]
at [Source: UNKNOWN; line: -1, column: -1]
此解决方案不符合我的要求:
Mathieu我最终决定创建自己的反序列化程序(而不是UniquePropertyDeserializer),在其中我使用内省来获取父类的字段。它允许避免在子类中再次指定所需的json属性
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Invalid type definition for type `Animals.Dog`: Argument #0 has no property name, is not Injectable: can not use as Creator [constructor for Animals.Dog, annotations: {interface com.fasterxml.jackson.annotation.JsonCreator=@com.fasterxml.jackson.annotation.JsonCreator(mode=DEFAULT)}]
at [Source: UNKNOWN; line: -1, column: -1]