gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:51:38 25 4
gpt4 key购买 nike

我需要有允许我序列化的功能 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 的一个实例时,它工作得很好,但是当我创建 map 并尝试序列化它时,jackson 跳过我的序列化程序并使用 StdKeySerializer . 如何解决???

感谢您的关注。

最佳答案

这个问题似乎与 Jackson 对通用对象的处理有关。解决此问题的一种方法是使用父类(super class)型标记来严格定义 map 类型。图解:

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

关于java - jackson map 序列化,键的自定义序列化器不被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13943488/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com