踩坑-FastJson解析问题

业务要求,从一些指定的接口获取json,然后转成指定的List<T>,我写的逻辑如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
private <T> List<T> fetchData(Supplier<BaseResp<Object>> supplier, Class<T> clazz) {
List<T> resultList = new ArrayList<>();
try {
BaseResp<Object> response = supplier.get();
log.debug("目标数据类型:{},数据长度:{}字符", clazz.getSimpleName(), response.toString().length());
if (response != null && response.getData() != null) {
resultList = parseJsonArray(JSON.toJSONString(response.getData().toString(), clazz));
}
} catch (Exception e) {
log.error("获取{}数据失败,原因: {}", clazz.getSimpleName(), e.getMessage());
}
return resultList;
}


private <T> List<T> parseJsonArray(String jsonData, Class<T> clazz) {
List<T> resultList = new ArrayList<>();
try (JSONReader reader = new JSONReader(new StringReader(jsonData))) {
reader.startArray();
while (reader.hasNext()) {
try {
resultList.add(reader.readObject(clazz));
} catch (Exception e) {
log.warn("解析单个数据时出错: {}", e.getMessage());
}
}
reader.endArray();
} catch (Exception e) {
log.error("解析JSON数组失败: {}", e.getMessage());
}
return resultList;
}

但是一直报错如下:

1
2
3
4
2024-08-06 10:28:14.871 [scheduling-1] WARN  com.kedacom.edu.component.course.he.service.SchoolCourseService - 解析单个数据时出错: syntax error, expect {, actual ident, pos 1, fastjson-version 1.2.83
2024-08-06 10:28:14.871 [scheduling-1] WARN com.kedacom.edu.component.course.he.service.SchoolCourseService - 解析单个数据时出错: syntax error, expect {, actual ident, pos 1, fastjson-version 1.2.83
2024-08-06 10:28:14.871 [scheduling-1] WARN com.kedacom.edu.component.course.he.service.SchoolCourseService - 解析单个数据时出错: syntax error, expect {, actual ident, pos 1, fastjson-version 1.2.83
2024-08-06 10:28:14.871 [scheduling-1] WARN com.kedacom.edu.component.course.he.service.SchoolCourseService - 解析单个数据时出错: syntax error, expect {, actual ident, pos 1, fastjson-version 1.2.83

解决方法很简单,把response.getData().toString()改成JSON.toJSONString(response.getData())即可。