jackson注释中的多态性:@JsonTypeInfo用法 [英] Polymorphism in jackson annotations: @JsonTypeInfo usage
问题描述
我想知道 @JsonTypeInfo
注释是否可用于接口。我有一组应该序列化和反序列化的类。
I would like to know if @JsonTypeInfo
annotation can be used for interfaces. I have set of classes which should be serialized and deserialized.
这是我正在尝试做的事情。我有两个实现类 Sub1
, Sub2
实现 MyInt
。某些模型类具有实现类型的接口参考。我想基于多态反序列化对象
Here is what I'm trying to do. I have two implementation classes Sub1
, Sub2
implementing MyInt
. Some of the model classes have the interface reference for the implementation types. I would like to deserialize the objects based on polymorphism
@JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=As.WRAPPER_OBJECT)
@JsonSubTypes({
@Type(name="sub1", value=Sub1.class),
@Type(name="sub2", value=Sub2.class)})
public interface MyInt{
}
@JsonTypeName("sub1")
public Sub1 implements MyInt{
}
@JsonTypeName("sub2")
public Sub2 implements MyInt{
}
我得到以下 JsonMappingException
:
意外的令牌(END_OBJECT),预期FIELD_NAME:需要包含类型id的JSON字符串
Unexpected token (END_OBJECT), expected FIELD_NAME: need JSON String that contains type id
推荐答案
@JsonSubTypes.Type必须具有一个值和这样的名字,
@JsonSubTypes.Type must have a value and a name like this,
@JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=As.WRAPPER_OBJECT, property="type")
@JsonSubTypes({
@JsonSubTypes.Type(value=Dog.class, name="dog"),
@JsonSubTypes.Type(value=Cat.class, name="cat")
})
在子类中,使用 @JsonTypeName(dog)
来表示名字。
In the subclass, use @JsonTypeName("dog")
to say the name.
'dog'和'cat'的值将在名为'type'的属性中设置。
The values 'dog' and 'cat' will be set in the property named 'type'.
这篇关于jackson注释中的多态性:@JsonTypeInfo用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!