首页 > 解决方案 > How to deserialize json to object using SubTypes?

问题描述

I need deserialize JSON to object depends on the type. I have the following JSON:

{
   "type": "dog",
   "name": "dogName"
}

and I have the following classes:

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
@JsonSubTypes({
        @JsonSubTypes.Type(value = Dog.class, name = "dog"),
        @JsonSubTypes.Type(value = Cat.class, name = "cat"),
})
public abstract class Animal {
    @JsonProperty("type")
    public String type;
    public String name;
}

public class Dog extends Animal {
   ...
}

public class Cat extends Animal {
   ...
}

and when I try to deserialize all is going fine:

public class StartPdfApp {
    public static void main(String[] args) throws IOException {
        ...
        ObjectMapper mapper = new ObjectMapper();
        Animal animal = mapper.readValue(json, Animal.class);
        System.out.println("TYPE: " + animal.type);        // always null
        System.out.println("DOG: " + (animal instanceof Dog));
        System.out.println("CAT: " + (animal instanceof Cat));
    }
}

but when I want to get field value type I have null How can I fix it?

标签: javajackson

解决方案


你需要告诉 Jackson 将 type 字段传递给反序列化器,否则它只用于类型区分。这是通过注释visible中的属性完成的。@JsonTypeInfo另外,不确定在您的情况下是否绝对必要,但我指定类型信息以使用现有属性:

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonTypeInfo(
    use = JsonTypeInfo.Id.NAME,
    include = JsonTypeInfo.As.EXISTING_PROPERTY,
    property = "type",
    visible = true)
@JsonSubTypes({
        @JsonSubTypes.Type(value = Dog.class, name = "dog"),
        @JsonSubTypes.Type(value = Cat.class, name = "cat"),
})
public abstract class Animal {
    @JsonProperty("type")
    public String type;
    public String name;
}

推荐阅读