[英]com.fasterxml.jackson.databind.JsonSerializer exclude fields by key
I have a class which I do not have control over it's source: 我有一个我无法控制其来源的课程:
public class SomeClassImpl implements SomeClass {
private SomeField someFiled; // Not serializable
... // Some other fields that are serializable
}
So this class is not fully Serializable
, and I am running into StackOverflowError
when I try to serialize it as json using Spring Boot as @ResponseBody
. 所以这个类不是完全可
Serializable
,当我尝试使用Spring Boot作为@ResponseBody
将其序列化为json时,我遇到了StackOverflowError
。
I have two controller methods: 我有两种控制器方法:
@ResponseBody public SomeClassImpl get();
@ResponseBody public SomeOtherClass find();
I have control over the source of SomeOtherClass
which includes SomeClass
as a property. 我可以控制
SomeOtherClass
的来源,其中包括SomeClass
作为属性。
I could not figure out how to ignore a field using @JsonIgnore
annotation, I probably need to to control the source.What I can do with annotations is that I can ignore SomeClass
property from SomeOtherClass
which does not help the first method above. 我无法弄清楚如何使用
@JsonIgnore
注释来忽略字段,我可能需要控制源。我可以做的是,我可以忽略SomeOtherClass
中的SomeClass
属性,该属性对上面的第一个方法没有帮助。 So I decided to implement JsonSerializer<SomeClassImpl>
: 所以我决定实现
JsonSerializer<SomeClassImpl>
:
@Override
public void serialize(SomeClassImpl someClass, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
// I need to write all fields except some
}
Or can I handle this with annotations? 还是可以通过注释来处理? If yes how?
如果是,怎么办? Thanks.
谢谢。
When modifying the source code is not an option, you can use mix-in annotations to add Jackson annotations to a bean. 如果无法修改源代码,则可以使用混合注释将Jackson注释添加到bean。
First define a mix-in annotation interface or class: 首先定义一个混合注解接口或类:
public interface FooMixIn {
@JsonIgnore
Object getBiz();
}
Then configure ObjectMapper
to use the defined interface as a mix-in for your POJO: 然后配置
ObjectMapper
以使用定义的接口作为POJO的混合:
ObjectMapper mapper = new ObjectMapper().addMixIn(Foo.class, FooMixIn.class);
private
, protected
, ...) and method implementations are ignored. private
, protected
,...)和方法实现将被忽略。 For more details, have a look at the Jackson documentation . 有关更多详细信息,请参阅Jackson 文档 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.