Jackson-jr读取多态ArrayList

时间:2016-09-20 21:14:55

标签: java json jackson

我正在使用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。一些链接,我找到杰克逊的答案,而不是杰克逊jr:

ClassCastException when convert json to list of objects

Jackson custom deserializer for one field with polymorphic types

Tricky(?) JSON, polymorphic deserialization

在Jackson-Jr中有处理这个问题吗?

1 个答案:

答案 0 :(得分:1)

您应该编程到接口而不是实现类。由于返回的地图实施为DeferredMap而非HashMap,因此您获得了ClassCastException。更改分配如下

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