Jackson 的 @JsonTypeInfo(use = Id.CUSTOM, include = As.PROPERTY, 属性 = "type") 读取 JSON 除了 "type" 的所有字段

Jackson's @JsonTypeInfo(use = Id.CUSTOM, include = As.PROPERTY, property = "type") reads all fields of JSON except for "type"

我逐行检查了每一行代码,但我认为这是 Jackson 在内部处理多态性的方式。

使用 DogCat 的 classic 示例扩展 Animal

@JsonTypeInfo(use = Id.CUSTOM, include = As.PROPERTY, property = "type")
@JsonTypeIdResolver(AnimalTypeIdResolver.class)
@JsonIgnoreProperties(ignoreUnknown = true)
public abstract class Animal implements Serializable {
    public AnnotatorBundleConfig(String name) {
        super();
        this.name = name;
    }

狗 class :

public class DogAnimal extends Animal {
    @JsonCreator
    public DogAnimal(
        @JsonProperty(value="name", required=true) String name,
        @JsonProperty(value="bark_decibel") int bark_decibel)
    {
    super(name);
    this.bark_decibel = bark_decibel;}

猫class:

public class CatAnimal extends Animal {
    @JsonCreator
    public CatAnimal(
        @JsonProperty(value="name", required=true) String name,
        @JsonProperty(value="meow_level") int meow_level)
    {
    super(name);
    this.meow_level = meow_level;}

AnimalTypeIdResolver 是一个典型的 TypeIdResolver 扩展 AbstractTypeIdResolver.

出于某些非常奇怪的原因,bark_decibelmeow_level 是从 JSON 反序列化的,但是 type 是作为 null 进入的。有什么想法吗?

@JsonTypeInfo 设置 visible=true

@JsonTypeInfo(use = Id.CUSTOM, include = As.PROPERTY, property = "type", visible=true)

参考this post