jackson map序列化,不调用键的自定义序列化器

Ph0*_*n1x 3 java serialization json jackson

我需要有功能,允许我序列化Map<CustomType1, CustomType2>.我创建了继承自JsonSerializer的自定义Serializer.我也创建了简单的模块并在我的mapper中注册它;

SimpleModule myModule = new SimpleModule("myModule");
myModule.addKeySerializer(CustomType1.class, new CustomType1Serializer());
myModule.addSerializer(CustomType1.class, new CustomType1Serializer());
mapperInstance.registerModule(myModule);
Run Code Online (Sandbox Code Playgroud)

当我只是序列化CustomType1的一个实例时它工作得很好,但是当我创建map并尝试序列化它时,jackson跳过我的序列化器并使用它StdKeySerializer.怎么解决???

感谢您的关注.

Per*_*ion 5

这个问题似乎与杰克逊对通用对象的处理有关.解决该问题的一种方法是使用超类型令牌来严格定义地图类型.图说:

final ObjectMapper mapper = new ObjectMapper();

final SimpleModule module = new SimpleModule("myModule",
        Version.unknownVersion());
module.addKeySerializer(CustomType1.class, new CustomType1Serializer());
mapper.registerModule(module);

final MapType type = mapper.getTypeFactory().constructMapType(
        Map.class, CustomType1.class, CustomType2.class);
final Map<CustomType1, CustomType2> map = new HashMap<CustomType1, CustomType2>(4);
final ObjectWriter writer = mapper.writerWithType(type);
final String json = writer.writeValueAsString(map);
Run Code Online (Sandbox Code Playgroud)