【发布时间】:2021-06-21 16:15:43
【问题描述】:
我有一个列表列表"[[2,3,5,7],[1,4,6]]"
如何使用 Jackson 将其转换为 Java ArrayList?任何参考资料或示例都可以。
【问题讨论】:
-
请告诉我们您尝试过的代码。你有什么问题?
-
其实我不知道如何解决这个问题,所以我问任何参考也可以工作
-
我相信谷歌搜索会帮助你。
我有一个列表列表"[[2,3,5,7],[1,4,6]]"
如何使用 Jackson 将其转换为 Java ArrayList?任何参考资料或示例都可以。
【问题讨论】:
这是使用 objectmapper 反序列化的泛型包装器,
public static <T> T fromJSON(final TypeReference<T> type,
final String jsonPacket) {
T data = null;
try {
data = new ObjectMapper().readValue(jsonPacket, type);
} catch (Exception e) {
// Handle the problem
}
return data;
例子
var list = "[[2,3,5,7],[1,4,6]]";
var result = JsonUtils.deserialize(new TypeReference<ArrayList<ArrayList<Integer>>>() {}, list);
【讨论】:
这里是一些使用TypeFactory的示例代码
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import java.util.ArrayList;
class Scratch {
public static void main(String[] args) throws JsonProcessingException {
final TypeFactory typeFactory = TypeFactory.defaultInstance();
final ArrayList<ArrayList<Integer>> data = new ObjectMapper().readValue("[[2,3,5,7],[1,4,6]]",
typeFactory.constructCollectionType(ArrayList.class,
typeFactory.constructCollectionType(ArrayList.class, Integer.class)));
System.out.println(data);
}
}
它构建对象并打印
[[2, 3, 5, 7], [1, 4, 6]]
【讨论】: