【问题标题】:Jackson-jr read polymorphic ArrayListJackson-jr 读取多态 ArrayList
【发布时间】:2017-01-28 22:52:41
【问题描述】:

我正在使用 Jackson-jr 来读取我的 JSON 文件。其中一个有点复杂:

[
 {"test-1":["a","b","c","d"]},
 {"test-2":["b","j","d"]},
 {"test-3":["n","e","o","p","i"]},
 {"test-4":["s","a","v","z","b","ç","x","p"]},
 {"test-5":["d","q","u"]},
 {"test-6":["f","b"]}
]

我的代码很简单:

InputStream inputStream   = assetManager.open("test.json");
ArrayList<HashMap<String, ArrayList<String>>> arrays = JSON.std.beanFrom(ArrayList.class, inputStream);

我的目的是让每个数组都能与它们一起工作:

arrays.get(i);

但是,当执行此行时,我有一个异常:

Caused by: java.lang.ClassCastException: com.fasterxml.jackson.jr.ob.impl.DeferredMap cannot be cast to java.util.HashMap

Jackson-jr 没有 TypeFactory、TypeReference 或 ObjectMapper。我为jackson找到了一些链接,而不是jackson-jr:

ClassCastException when convert json to list of objects

Jackson custom deserializer for one field with polymorphic types

Tricky(?) JSON, polymorphic deserialization

Jackson-Jr 有处理这个问题的说法吗?

【问题讨论】:

  • arrays定义为List&lt;Map&lt;String, List&lt;String&gt;&gt;&gt; arrays
  • 你拯救了一天。谢谢。

标签: java json jackson


【解决方案1】:

您应该对接口而不是实现类进行编程。由于返回的 Map 实现是 DeferredMap 而不是 HashMap,因此您会得到 ClassCastException。如下更改分配

List<Map<String, List<String>>> arrays = JSON.std.beanFrom(ArrayList.class, inputStream);

【讨论】:

  • 此外,使用的方法应该是listOfFrom,而不是beanFrom,因为结果是List,而不是Bean。如果是这样,类型将是Map.class
猜你喜欢
  • 1970-01-01
  • 2016-11-03
  • 2013-09-22
  • 2013-11-09
  • 2015-01-31
  • 1970-01-01
  • 1970-01-01
  • 2014-11-11
  • 2020-05-23
相关资源
最近更新 更多