【问题标题】:jackson map serialization, custom serializer for the key do not invoked杰克逊地图序列化,不调用键的自定义序列化程序
【发布时间】:2012-12-18 23:58:10
【问题描述】:

我需要具有允许我序列化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如何解决这个问题???

感谢您的关注。

【问题讨论】:

    标签: java json serialization jackson


    【解决方案1】:

    这个问题似乎与杰克逊对通用对象的处理有关。解决此问题的一种方法是使用超类型标记来严格定义映射类型。图解:

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

    【讨论】:

    • 非常感谢您的帮助 =)
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2016-02-19
      • 1970-01-01
      • 2017-06-16
      • 2012-01-11
      • 2017-01-30
      • 1970-01-01
      • 2016-01-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多