簡體   English   中英

jackson map序列化,不調用鍵的自定義序列化器

[英]jackson map serialization, custom serializer for the key do not invoked

我需要具有允許我序列化Map<CustomType1, CustomType2> 我創建了繼承自JsonSerializer的自定義Serializer。 我也創建了簡單的模塊並在我的mapper中注冊它;

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

當我只是序列化CustomType1的一個實例時它工作得很好,但是當我創建map並嘗試序列化它時,jackson跳過我的序列化器並使用StdKeySerializer 怎么解決???

感謝您的關注。

這個問題似乎與傑克遜對通用對象的處理有關。 解決該問題的一種方法是使用超類型令牌來嚴格定義地圖類型。 圖說:

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

addSerializer和addKeySerializer只是兩種類型的可用序列化程序,只處理簡單的非POJO類型。 要為更復雜的類型(如地圖和集合)進行自定義序列化,需要在模塊上使用.setSerializerModifier,BeanSerializerModifier將覆蓋modifyMapSerializer方法並返回自定義序列化程序

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM