杰克逊注解中的多态性:@JsonTypeInfo 用法

我想知道 @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.

这就是我想要做的.我有两个实现类 Sub1Sub2 实现 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:需要 JSON 字符串包含类型 id

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") 说出名字.
dogcat 值将在名为 type 的属性中设置.

In the subclass, use @JsonTypeName("dog") to say the name.
The values dog and cat will be set in the property named type.

相关文章