如何防止 Jackson 序列化多态类型的注释属性?
我有多态类型和从 JSON 到 POJO 的反序列化工作。事实上,我按照此处的文档进行操作。将 POJO 序列化为 JSON 时,我得到了一个不需要的属性,特别是逻辑类型名称。
import static org.codehaus.jackson.annotate.JsonTypeInfo.*;
@JsonTypeInfo(use=Id.NAME, include=As.PROPERTY, property="type")
@JsonSubTypes({
@JsonSubTypes.Type(value=Dog.class, name="dog"),
@JsonSubTypes.Type(value=Cat.class, name="cat")
})
public class Animal { ... }
public class Dog extends Animal { ... }
public class Cat extends Animal { ... }
当 Jackson 序列化为 JSON 时,它提供了我不想公开的类型信息。
{"type":"dog", ... }
{"type":"cat", ... }
我可以以某种方式阻止这种情况吗?我只想在反序列化时忽略 type
。
I have polymorphic types and deserializing from JSON to POJO works. I followed the documentation here, in fact. When serializing POJOs into JSON I'm getting an unwanted attribute, specifically the logical type name.
import static org.codehaus.jackson.annotate.JsonTypeInfo.*;
@JsonTypeInfo(use=Id.NAME, include=As.PROPERTY, property="type")
@JsonSubTypes({
@JsonSubTypes.Type(value=Dog.class, name="dog"),
@JsonSubTypes.Type(value=Cat.class, name="cat")
})
public class Animal { ... }
public class Dog extends Animal { ... }
public class Cat extends Animal { ... }
When Jackson serializes into JSON it provides the type information which I don't want to expose.
{"type":"dog", ... }
{"type":"cat", ... }
Can I prevent this somehow? I only want to ignore type
when deserializing.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这花了我很长时间才解决,所以我想我会分享。
visible=false
确保如果类中存在属性type
,则在反序列化期间不会用type
的值填充该属性。include = JsonTypeInfo.As.EXISTING_PROPERTY
指示如果属性type
存在,则在序列化期间使用该值,否则不执行任何操作。所以把它们放在一起:
This took me a long time to solve so I thought I'd share.
visible=false
ensures that if the propertytype
exists on the class, it will not be populated with the value oftype
during deserialization.include = JsonTypeInfo.As.EXISTING_PROPERTY
dictates that if the propertytype
exists, use that value during serialization otherwise do nothing.So putting it all together:
一个简单的解决方案是将
@JsonTypeInfo
和@JsonSubTypes
配置移动到MixIn
,然后仅注册MixIn< /code> 用于反序列化。
mapper.getDeserializationConfig().addMixInAnnotations(MyClass.class, MyMixIn.class)
A simple solution would be to just move the
@JsonTypeInfo
and@JsonSubTypes
configs to aMixIn
, and then only register theMixIn
for deserialization.mapper.getDeserializationConfig().addMixInAnnotations(MyClass.class, MyMixIn.class)