Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson: in case of multiple serializers which one is used?

I am using Jackson to serialize POJOs. I wrote a custom serializer for string values, and it works fine.

However I am not sure what happens, when two serializers are registered for the same type. In my tests the last one added was used, but I am not sure whether it works that way all the time or not.

So my question is: if I add multiple serializers for the same type, which one will be used?


Code snippet:

objectMapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(new CustomSerializer1());
module.addSerializer(new CustomSerializer2());

...

class CustomSerializer1 extends NonTypedScalarSerializerBase<String>
class CustomSerializer2 extends NonTypedScalarSerializerBase<String>
like image 801
Marcell Avatar asked Oct 29 '22 07:10

Marcell


1 Answers

In an ideal world, something like this would be clearly specified in the Javadoc of SimpleModule, but it unfortunately doesn't seem to be the case here.

The next-best approach is to look at the source, which reveals that SimpleModule uses the class SimpleSerializers to keep track of its configured serializers.

Diving into that reveals the _addSerializer method:

protected void _addSerializer(Class<?> cls, JsonSerializer<?> ser)
{
    ClassKey key = new ClassKey(cls);
    // Interface or class type?
    if (cls.isInterface()) {
        if (_interfaceMappings == null) {
            _interfaceMappings = new HashMap<ClassKey,JsonSerializer<?>>();
        }
        _interfaceMappings.put(key, ser);
    } else { // nope, class:
        if (_classMappings == null) {
            _classMappings = new HashMap<ClassKey,JsonSerializer<?>>();
        }
        _classMappings.put(key, ser);
        if (cls == Enum.class) {
            _hasEnumSerializer = true;
        }
    }
}

Conclusion is the same as the one you've already reached: The last added serializer is used, due to them being stored in a Map with their input type as keys. Strictly speaking, there are no guarantees that this will not change in the future though, as it is all internal implementation.

like image 153
Henrik Aasted Sørensen Avatar answered Nov 09 '22 13:11

Henrik Aasted Sørensen