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. 怎么解决???

感谢您的关注。

4

2 回答 2

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);
于 2012-12-19T01:33:51.540 回答
1

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

于 2017-06-24T22:23:25.083 回答