简体   繁体   English

使用注释的Jackson多态反序列化

[英]Jackson polymorphic deserialization using annotations

Assume we have the following types: 假设我们有以下几种类型:

interface Animal {}
class Dog implements Animal {...}
class Cat implements Animal {...}
class Zoo {
    private String animalType;
    private Animal animal;
    ...
}

Having that Cat and Dog have different properties, how can we deserialize Zoo object to appropriate Animal subtype based on animalType string which is always present in json ? 假设CatDog具有不同的属性,我们如何基于json中始终存在的animalType字符串反序列化Zoo对象为适当的Animal子类型? I know how to do that with custom deserialization but i can't find the way to do the same using Jackson annotations . 我知道如何使用custom deserialization来做到这一点,但是我找不到使用Jackson annotations进行同样操作的方法。 This would be possible if animalType property resides in Cat or Dog but in my case its location is in Zoo . 如果animalType属性驻留在CatDog但在我的情况下,其位置在Zoo

Any idea ? 任何想法 ?

You can annotate the animal field in Zoo with JsonTypeInfo to specify which subtype you want Dog or Cat per the animalType field also in Zoo . 您可以使用JsonTypeInfo注释Zooanimal字段,以在Zoo也根据每个animalType字段指定要使用DogCat子类型。 The tricky bit is to specify that the specific type of Animal will come from a property outside of Animal in the JSON ie an EXTERNAL_PROPERTY 棘手的一点是,指定Animal的特定类型将来自JSON中Animal之外的属性,即EXTERNAL_PROPERTY

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXTERNAL_PROPERTY, property = "animalType")
@JsonSubTypes({
        @JsonSubTypes.Type(value = Cat.class, name = "cat"),
        @JsonSubTypes.Type(value = Dog.class, name = "dog")
})
private Animal animal;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM