Reputation: 163
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>
Upvotes: 7
Views: 3260
Reputation: 7157
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.
Upvotes: 5