Jackson custom JsonSerializer - conditionally call default serializer

倾然丶 夕夏残阳落幕 提交于 2020-02-12 04:23:10

问题


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
        }
    }
}

I've tried to do something like that:

serializerProvider.defaultSerializeValue(o, jsonGenerator);

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?


回答1:


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.



来源:https://stackoverflow.com/questions/30028407/jackson-custom-jsonserializer-conditionally-call-default-serializer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!