Apply default serializer to properties in custom serializer with Jackson

631 views Asked by At

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.

1

There are 1 answers

0
StaxMan On

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(). It is given the default serializer, and you can then construct your own, which can then delegate as it sees fit.