编程语言
首页 > 编程语言> > java-杰克逊的@JsonTypeInfo(use = Id.CUSTOM,include = As.PROPERTY,property =“ type”)读取JSON的所有字段(“ type”除外

java-杰克逊的@JsonTypeInfo(use = Id.CUSTOM,include = As.PROPERTY,property =“ type”)读取JSON的所有字段(“ type”除外

作者:互联网

我逐步完成了每一行代码,但是我认为这就是Jackson内部处理多态性的方式.

使用狗和猫扩展动物的经典示例:

@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;
    }

狗类:

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;}

猫类:

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是扩展AbstractTypeIdResolver的典型TypeIdResolver.

出于某些非常奇怪的原因,bark_decibel和meow_level从JSON反序列化,但是type以null形式进入.有任何想法吗?

解决方法:

为@JsonTypeInfo设置visible = true:

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

参考this post

标签:jackson2,jackson,json,java
来源: https://codeday.me/bug/20191118/2025829.html