Jackson custom JsonSerializer - conditionally call default serializer
Asked Answered
N

1

7

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?

Neat answered 4/5, 2015 at 10:58 Comment(0)
A
3

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.

Adventurism answered 4/5, 2015 at 22:1 Comment(2)
OK, that was what I was looking for, thanks. I also found similar question with more detailed description: #14714828Debouchment
Ok good. This is not a rare use case, but it is quite tricky to support wrt fallbacks. Glad you were able to get it worked out.Adventurism

© 2022 - 2024 — McMap. All rights reserved.