[英]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 ? 假设
Cat
和Dog
具有不同的属性,我们如何基于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
属性驻留在Cat
或Dog
但在我的情况下,其位置在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
注释Zoo
的animal
字段,以在Zoo
也根据每个animalType
字段指定要使用Dog
或Cat
子类型。 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.