我正在使用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)有处理这个问题的说法吗?
最佳答案
您应该对接口进行编程,而不要对实现类进行编程。由于返回的Map实现是DeferredMap
而不是HashMap
,因此得到ClassCastException
。如下更改作业
List<Map<String, List<String>>> arrays = JSON.std.beanFrom(ArrayList.class, inputStream);