Jackson:如果有多个序列化程序,使用哪一个?

Mar*_*ell 5 java serialization json jackson

我正在使用Jackson来序列化 POJO。我为字符串值编写了一个自定义序列化程序,它工作正常。

但是,当两个序列化程序注册为相同类型时,我不确定会发生什么。在我的测试中,使用了最后一个添加的,但我不确定它是否一直都这样工作。

所以我的问题是:如果我为同一类型添加多个序列化程序,将使用哪一个?


代码片段:

objectMapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(new CustomSerializer1());
module.addSerializer(new CustomSerializer2());
Run Code Online (Sandbox Code Playgroud)

...

class CustomSerializer1 extends NonTypedScalarSerializerBase<String>
class CustomSerializer2 extends NonTypedScalarSerializerBase<String>
Run Code Online (Sandbox Code Playgroud)

Hen*_*sen 5

在理想的情况下,类似这样的事情会在 的 Javadoc 中明确指定SimpleModule,但不幸的是,这里的情况似乎并非如此。

下一个最佳方法是查看源代码,它揭示了SimpleModule使用该类SimpleSerializers来跟踪其配置的序列化器。

深入研究揭示了该_addSerializer方法:

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

结论与您已经达到的结论相同:使用最后添加的序列化器,因为它们存储在 a 中Map,其输入类型作为键。严格来说,不能保证这在未来不会改变,因为这都是内部实现。

  • 链接已损坏。新网址:https://github.com/FasterXML/jackson-databind/blob/2.15/src/main/java/com/fasterxml/jackson/databind/module/SimpleSerializers.java#L227 (2认同)