[英]Apply default serializer to properties in custom serializer with Jackson
I have an object that needs serialization, but I've run into a bit of a wall. 我有一个需要序列化的对象,但是我碰到了一堵墙。 I needed a custom serializer to serialize differently an invalid object vs a valid one.
我需要一个自定义序列化程序,以对无效对象和有效对象进行不同的序列化。 As such, I wrote a custom serializer that looks like:
因此,我编写了一个自定义序列化器,如下所示:
public class MySerializer extends JsonSerializer<MyObject> {
@Override
public void serialize(MyObject obj, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
jgen.writeStartObject();
if(obj.isValid()){
jgen.writeObject(obj.getInvalids());
}
else{
jgen.writeObject(obj);
}
jgen.writeEndObject();
}
}
Now I'm getting an error if infinite recursion when I try to serialize (for reasons that are quite clear). 现在,当尝试序列化时,如果无限递归,我会收到一个错误消息(原因很明确)。 So I'm wondering if I can do this without having to change my code to something like:
所以我想知道是否可以在不必将代码更改为类似的情况下执行此操作:
public class MySerializer extends JsonSerializer<MyObject> {
@Override
public void serialize(MyObject obj, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
jgen.writeStartObject();
if(obj.isValid()){
jgen.writeObject(obj.getInvalids());
}
else{
jgen.writeObjectField("prop1", obj.getProp1());
jgen.writeObjectField("prop2", obj.getProp2());
...
}
jgen.writeEndObject();
}
}
Is there a cleaner way (and less annoying) way to do what I'm trying to do? 是否有一种更干净(且较不烦人)的方式来完成我要尝试的操作? I've seen this answer to a similar question, but it is quite terse and I was unable to divine a clear solution from it.
我已经看到了对类似问题的答案,但这非常简洁,我无法从中找到明确的解决方案。
The way to get access to "default" serializer (one that Jackson would build if you didn't provide custom one) is by registering a BeanSerializerModifier
(use SimpleModule
to register it), and then override modifySerializer()
. 访问“默认”序列化程序(如果您不提供自定义序列号,则将由Jackson生成)的访问方式是注册
BeanSerializerModifier
(使用SimpleModule
进行注册),然后重写modifySerializer()
。 It is given the default serializer, and you can then construct your own, which can then delegate as it sees fit. 它具有默认的序列化程序,然后您可以构造自己的序列化程序,然后在合适的时候委托它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.