2012-12-18 45 views
3

我需要有功能,它允许我序列化Map<CustomType1, CustomType2>。 我创建了从JsonSerializer继承的自定义序列化器。 我也创建了简单的模块并将其注册到我的映射器中;杰克逊映射序列化,自定义序列化的关键不调用

SimpleModule myModule = new SimpleModule("myModule"); 
myModule.addKeySerializer(CustomType1.class, new CustomType1Serializer()); 
myModule.addSerializer(CustomType1.class, new CustomType1Serializer()); 
mapperInstance.registerModule(myModule); 

当我刚刚序列化CustomType1的一个实例,它完美的作品,但是当我创建的地图,并试图将其序列化,比杰克逊跳过我的串行和使用StdKeySerializer如何解决?

感谢您的关注。

回答

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); 
+0

非常适合您的帮助=) – Ph0en1x

0

addSerializer和addKeySerializer只是两种类型,只有简单的,非POJO类型的处理可序列化的。要为更复杂的类型(例如映射和集合)定制序列化,您需要在模块上使用.setSerializerModifier,并使用BeanSerializerModifier来覆盖modifyMapSerializer方法并返回您的自定义串行器。