gpt4 book ai didi

java - Jackson-jr 读取多态ArrayList

转载 作者:行者123 更新时间:2023-11-30 07:08:38 29 4
gpt4 key购买 nike

我正在使用 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 有办法处理这个问题吗?

最佳答案

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

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

关于java - Jackson-jr 读取多态ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39603834/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com