如何更改杰克逊的默认具体地图类型? [英] How to change Jackson's default concrete map type?

查看:85
本文介绍了如何更改杰克逊的默认具体地图类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的Jackson代码来反序列化嵌套的JSON对象:

I have a very simple Jackson code to deserialize a nested JSON object:

public class MapTest
{
  public static void main(String ... args) throws Exception
  {
    final String ser = "{\"nested\":{\"k1\":\"v1\",\"k2\":\"v2\",\"k3\":\"v3\"}}";
    final Map<String, Object> deser = new ObjectMapper().readValue(ser, new TypeReference<TreeMap<String, Object>>(){});
    System.out.println("Class of deser's nested object is " + deser.get("nested").getClass().getSimpleName());
  }
}

当我运行此操作时,我获得以下输出:

When I run this I obtain the following output:

Class of deser's nested object is LinkedHashMap

但是我想将嵌套地图反序列化为 TreeMap 而不是 LinkedHashMap 根据输出。在反序列化时如何告诉Jackson默认使用 TreeMap

However I want the nested map to be deserialized as a TreeMap rather than as a LinkedHashMap as per the output. How can I tell Jackson to default to use a TreeMap when deserializing?

通过文档阅读最接近的文件我发现是能够通过模块中的 addAbstractTypeMapping()为抽象类型定义具体类,但我已经尝试了每个超类和 LinkedHashMap的实例尝试这样做似乎没什么用。

Reading through the documentation the closest thing I found was the ability to define concrete classes for abstract types through addAbstractTypeMapping() in a module but I've tried every superclass and instance of LinkedHashMap in an attempt to do this and nothing seems to work.

这是使用Jackson 2.4.2,虽然如果有办法做到这一点需要更高的版本才能升级。

This is using Jackson 2.4.2, although if there is a way to do this that requires a higher version I would be able to upgrade.

推荐答案

模块的 addAbstractTypeMapping()确实是实现映射的方法。但问题可能是由于反序列化的递归性质;因为内部值被认为是类型java.lang.Object

Module's addAbstractTypeMapping() is indeed the way to achive mapping in general. But the problem may be due to recursive nature of deserialization; because inner values are considered to be of type java.lang.Object.

但是,我认为确实存在修复了2.5中的这一部分,所以我会专门检查2.5.0是否可行,一旦你从 Map 添加抽象映射到 TreeMap
如果这不起作用,请在 https://github.com/上提交错误FasterXML / jackson-databind / issues 因为它应该可以工作。

However, I think there were indeed fixes to this part in 2.5, so I would specifically checking to see if 2.5.0 would work, once you add abstract mapping from Map to TreeMap. If this does not work, please file a bug at https://github.com/FasterXML/jackson-databind/issues since it should work.

这篇关于如何更改杰克逊的默认具体地图类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆