Java jackson映射序列化,不调用密钥的自定义序列化程序

Java jackson映射序列化,不调用密钥的自定义序列化程序,java,json,serialization,jackson,Java,Json,Serialization,Jackson,我需要一个函数,它允许我序列化Map。 我创建从JsonSerializer继承的自定义序列化程序。 我还创建了简单的模块,并将其注册到我的映射器中 SimpleModule myModule = new SimpleModule("myModule"); myModule.addKeySerializer(CustomType1.class, new CustomType1Serializer()); myModule.addSerializer(CustomType1.class, new

我需要一个函数,它允许我序列化
Map
。 我创建从JsonSerializer继承的自定义序列化程序。 我还创建了简单的模块,并将其注册到我的映射器中

SimpleModule myModule = new SimpleModule("myModule");
myModule.addKeySerializer(CustomType1.class, new CustomType1Serializer());
myModule.addSerializer(CustomType1.class, new CustomType1Serializer());
mapperInstance.registerModule(myModule);
当我只是序列化CustomType1的一个实例时,它工作得很好,但是当我创建映射并尝试序列化它时,jackson跳过了我的序列化程序并使用
StdKeySerializer
如何解决这个问题?


感谢您的关注。

这个问题似乎与Jackson处理通用对象有关。解决此问题的一种方法是使用超级类型令牌严格定义映射类型。插图:

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);
final ObjectMapper mapper=new ObjectMapper();
最终SimpleModule=新SimpleModule(“myModule”,
Version.unknownVersion());
module.addKeySerializer(CustomType1.class,新的CustomType1Serializer());
映射器注册表模块(模块);
final MapType type=mapper.getTypeFactory().constructMapType(
Map.class、CustomType1.class、CustomType2.class);
最终映射=新的HashMap(4);
最终ObjectWriter writer=mapper.writerWithType(类型);
最后一个字符串json=writer.writeValueAsString(map);

addSerializer和addKeySerializer只是两种可用的序列化程序,它们只处理简单的非POJO类型。要对更复杂的类型(如映射和集合)进行自定义序列化,您需要在模块上使用.setSerializerModifier,并使用BeanSerializerModifier覆盖modifyMapSerializer方法并返回自定义序列化程序(非常感谢您的帮助=)