java 如何防止 Jackson 序列化多态类型的注释属性?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5826928/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I prevent Hymanson from serializing a polymorphic type's annotation property?
提问by Loc Nguyen
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.
我有多态类型和从 JSON 反序列化到 POJO 的工作。事实上,我遵循了此处的文档。将 POJO 序列化为 JSON 时,我得到了一个不需要的属性,特别是逻辑类型名称。
import static org.codehaus.Hymanson.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 Hymanson serializes into JSON it provides the type information which I don't want to expose.
当 Hymanson 序列化为 JSON 时,它提供了我不想公开的类型信息。
{"type":"dog", ... }
{"type":"cat", ... }
Can I prevent this somehow? I only want to ignore type
when deserializing.
我可以以某种方式防止这种情况吗?我只想type
在反序列化时忽略。
采纳答案by Programmer Bruce
A simple solution would be to just move the @JsonTypeInfo
and @JsonSubTypes
configs to a MixIn
, and then only register the MixIn
for deserialization.
一个简单的解决方案是将@JsonTypeInfo
和@JsonSubTypes
配置移动到 a MixIn
,然后只注册MixIn
反序列化。
mapper.getDeserializationConfig().addMixInAnnotations(MyClass.class, MyMixIn.class)
mapper.getDeserializationConfig().addMixInAnnotations(MyClass.class, MyMixIn.class)
回答by karmcoder
This took me a long time to solve so I thought I'd share.
这花了我很长时间才解决,所以我想我会分享。
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY,
visible = false, property = "type")
visible=false
ensures that if the property type
exists on the class, it will not be populated with the value of type
during deserialization.
visible=false
确保如果该属性type
存在于类中,则type
在反序列化期间不会使用 的值填充它。
include = JsonTypeInfo.As.EXISTING_PROPERTY
dictates that if the property type
exists, use that value during serialization otherwise do nothing.
include = JsonTypeInfo.As.EXISTING_PROPERTY
指示如果该属性type
存在,则在序列化期间使用该值,否则什么都不做。
So putting it all together:
所以把它们放在一起:
import static org.codehaus.Hymanson.annotate.JsonTypeInfo.*;
@JsonTypeInfo(use = Id.NAME, include = As.EXISTING_PROPERTY, visible = false, 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 { ... }