我正在使用Jackson序列化POJO。我为字符串值编写了一个自定义序列化程序,并且工作正常。
但是,我不确定将两个序列化器注册为同一类型时会发生什么。在我的测试中,使用了最后添加的一个,但是我不确定它是否一直都这样工作。
所以我的问题是:如果我为同一类型添加多个序列化器,将使用哪一个?
程式码片段:
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>
在理想的世界中,的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;
}
}
}
结论与您已经获得的结论相同:使用最后添加的序列化程序,因为它们Map
以输入类型作为键存储在中。严格来讲,不能保证将来不会改变,因为它全部是内部实现。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句