Java 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)

我目前正在尝试使用jackson实现一个反序列化程序,该程序能够处理多态性,也就是说,给定以下两个类:

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]
此解决方案不符合我的要求:

  • 每次我们想要创造一个新的动物亚类,我们必须 在此类中指定名称和权重是json属性

  • 这是一个棘手的问题,例如,在Animal类中,weight属性被标记为required,而在子类中,我们可以定义weight不是required属性

  • 您知道一种从父类的属性“继承”的方法吗,以避免每次在子类中指定相应的json属性

    致以最良好的祝愿


    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]