javajacksonjackson-databind

Jackson serialization for a specific static object


I am trying to serialize a list which contains objects I cannot manipulate. That list contains a reference to a static object:

final public static Object NULL_VALUE = new Object() { public String toString() { return "null"; }};

How can I tell Jackson to serialize NULL_VALUE object as null? I tried the following:

public class NullValueSerializer extends StdSerializer<Object> {
    public NullValueSerializer() {
        super(Object.class);
    }

    @Override
    public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (value == Jsonata.NULL_VALUE) {
            gen.writeNull();
        } else {
            gen.writePOJO(value);
        }
    }
}

I hoped that this would work, but it obviously ends up in a StackOverflowError because the serializer calls itself recursively. I do not know if there is a different approach, but I cannot find anything related to this in the documentation.

Is there a way to serialize this value as null?


Solution

  • So, you should definitely write a custom serializer, but the type you should serializer isn't Object (which isn't a specific serializer - it will be called for everything, as you've discovered). You should write a serializer that serializes the anonymous inner type that is the actual type of the NULL_VALUE instance.

    You can register your custom serializer by referencing the actual type, like so:

    SimpleModule module = new SimpleModule();
    module.addSerializer(ThatType.NULL_VALUE.getClass(), new NullValueSerializer());
    mapper.registerModule(module);