问题描述
我想要的是对我的班级对象有条件地使用默认BeanSerializer:
What I want is to use default BeanSerializer conditionally for my class's objects:
class MyCustomSerializer extends StdSerializer<AbstractEntity> {
public MyCustomSerializer() {
super(AbstractEntity.class);
}
@Override
public void serialize(AbstractEntity o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
if (someCondition()) {
serializeNormalWay(); //how?
} else {
//custom serialization
}
}
}
我试图做类似的事情:
serializerProvider.defaultSerializeValue(o, jsonGenerator);
但这会调用MyCustomSerializer的方法,而且我有永无止境的递归。
如何获得适当的Serializer对象,我可以用于普通bean序列化?
but this calls MyCustomSerializer's method and I have never-ending recursion.How can I get appropriate Serializer object, that I could use for ordinary bean Serialization?
推荐答案
这需要更复杂的设置:而不是直接覆盖串行器使用,你需要让杰克逊创建一个,然后采取过度。
这可以通过注册 BeanSerializerModifier
(通过模块
),方法 modifySerializer来完成(...)
。您将获得将使用的默认序列化程序,您可以构建自定义序列化程序,并传递默认序列化程序。
This requires bit more complicated setup: instead of directly overriding serializer to use, you need to let Jackson create one, then take over.This may be done by registering BeanSerializerModifier
(via Module
), method modifySerializer(...)
. You will be given default serializer that would be used, and you can construct custom one, passing that default one.
这篇关于Jackson自定义JsonSerializer - 有条件地调用默认序列化程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!