gpt4 book ai didi

java ; jackson ;解析数组json字符串的数组

转载 作者:行者123 更新时间:2023-12-02 01:45:15 28 4
gpt4 key购买 nike

我发现使用 jackson api 将下面的 json 解析为 java 对象时出现问题。

Json String
[
[
{
"id": "6555",
"fname": "hello",
"lname": "test"
},
{
"id": "6588",
"fname": "world",
"lname": "test"
}
]
]

我创建了以下 pojo(删除了 setter 和 getter)。

public class Result {
List<Student> studentList;
}

public class Student{
private String id;
private String fname;
private String lname;
}

ObjectMapper mapper = new ObjectMapper();
List<Result > responseList = mapper.readValue(jsonStr, new TypeReference<List<Result>>(){});

jackson 抛出异常

com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of out of START_ARRAY token at [Source:

我需要对 Result 对象进行任何特定的 Jackson 注释吗?

最佳答案

你不需要 Result 类,它是多余的。您需要将其解析为 List<List<Student>>因为您的 json 结构以数组开头并包含另一个数组。

以下是如何解析您的:

ObjectMapper mapper = new ObjectMapper();
try {
List<Result> responseList = mapper.readValue(
Files.readAllBytes(Paths.get("test.json")),
new TypeReference<List<List<Student>>>() {});

} catch (IOException e) {
e.printStackTrace();
}

输出:

enter image description here

关于 java ; jackson ;解析数组json字符串的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53768743/

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