杰克逊注解中的多态性:@JsonTypeInfo 用法 [英] Polymorphism in jackson annotations: @JsonTypeInfo usage

查看:70
本文介绍了杰克逊注解中的多态性:@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.

这篇关于杰克逊注解中的多态性:@JsonTypeInfo 用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆