跳至主要內容
  • Hostloc 空間訪問刷分
  • 售賣場
  • 廣告位
  • 賣站?

4563博客

全新的繁體中文 WordPress 網站
  • 首頁
  • Jackson 序列化时,如何将 final 类型的类型信息保存起来?
未分類
19 7 月 2020

Jackson 序列化时,如何将 final 类型的类型信息保存起来?

Jackson 序列化时,如何将 final 类型的类型信息保存起来?

資深大佬 : JasonLaw 20

先看一下以下代码了解问题

ObjectMapper objectMapper = new ObjectMapper()                 .enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);  //        Map<Integer, Integer> map1 = new HashMap<>(); //        map1.put(1, 1);         Map<Integer, Integer> map1 = ImmutableMap.of(1, 1);                  // 使用 HashMap 时,content 是`["java.util.HashMap",{"1":1}]`;而使用 ImmutableMap 时是`{"1":1}`         String content = objectMapper.writeValueAsString(map1);         // 因为使用 ImmutableMap 时没有了类型信息,反序列化会报错。         // com.fasterxml.jackson.databind.exc.MismatchedInputException: Unexpected token (START_OBJECT), expected START_ARRAY: need JSON Array to contain As.WRAPPER_ARRAY type information for class java.util.Map  at [Source: (String)"{"1":1}"; line: 1, column: 1]         Map<Integer, Integer> map2 = objectMapper.readValue(content, new TypeReference<Map<Integer, Integer>>() {         }); 

按照JacksonPolymorphicDeserialization · FasterXML/jackson-docs Wiki所描述的,如果我没有理解错的话,使用 ImmutableMap 时没有保存类型信息是因为ImmutableMap.of(1, 1)会产生SingletonImmutableBiMap,而SingletonImmutableBiMap是 final 的。

但是四种ObjectMapper.DefaultTyping( JAVA_LANG_OBJECT, OBJECT_AND_NON_CONCRETE, NON_CONCRETE_AND_ARRAYS, NON_FINAL )都无法实现“保存SingletonImmutableBiMap这个类型信息”。而ObjectMapper.setDefaultTyping(...)也是依赖于ObjectMapper.DefaultTyping的,所以也不行。

问题:Jackson 能够保存 final 类型的类型信息吗?如果可以的话,应该怎么做呢?

大佬有話說 (6)

  • 資深大佬 : xgfan

    试过 activateDefaultTypingAsProperty 吗?

  • 資深大佬 : xgfan

    改成 ObjectMapper.DefaultTyping.EVERYTHING,就能保存了。
    [“com.google.common.collect.SingletonImmutableBiMap”,{“1”:1}]
    但是没办法反序列化,因为这玩意儿没有构造器。

  • 主 資深大佬 : JasonLaw

    @xgfan #2 谢谢提示

  • 主 資深大佬 : JasonLaw

    我现在的处理方式是使用 HashMap 作为“中间人”来实现 ImmutableMap 的序列化和反序列化。参考 https://stackoverflow.com/a/34115875/5232255

  • 資深大佬 : azygote

    你需要这个包 https://github.com/FasterXML/jackson-datatypes-collections 来进行 Guava 里面的一些 Collections 类的序列 /反序列化

  • 主 資深大佬 : JasonLaw

    @azygote #5 谢谢

文章導覽

上一篇文章
下一篇文章

AD

其他操作

  • 登入
  • 訂閱網站內容的資訊提供
  • 訂閱留言的資訊提供
  • WordPress.org 台灣繁體中文

51la

4563博客

全新的繁體中文 WordPress 網站
返回頂端
本站採用 WordPress 建置 | 佈景主題採用 GretaThemes 所設計的 Memory
4563博客
  • Hostloc 空間訪問刷分
  • 售賣場
  • 廣告位
  • 賣站?
在這裡新增小工具