Polymorphism in jackson annotations: @JsonTypeInfo usage(杰克逊注解中的多态性:@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.
这就是我想要做的.我有两个实现类 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:需要 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") 说出名字.dog 和 cat 值将在名为 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 用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:杰克逊注解中的多态性:@JsonTypeInfo 用法
基础教程推荐
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- Struts2 URL 无法访问 2022-01-01
