java - 如何将 JSONObject 解析为整数列表?
问题描述
我有一个这样的json文件。
{
"student": [
{
"name": "takeru",
"id": 23,
},
{
"name": "george",
"id": 43,
},
{
"name": "hans",
"id": 45,
}
],
"cost": 100,
"month": 6
}
我想要做的是将所有学生 ID 存储在 ArrayList 中?
解决方案
首先,您的“JSON 文件”不是有效的 JSON。你有多余的逗号。
假设您的文件是有效的 JSON,您可以使用库来解析 JSON。我推荐Gson。下面是使用 Gson 的代码:
static List<Integer> storeStudentIds(Path file) throws IOException {
Gson gson = new Gson();
try (Reader r = Files.newBufferedReader(file)) {
StudentGroup group = gson.fromJson(r, StudentGroup.class);
return group.student.stream().map(s -> s.id).collect(Collectors.toList());
}
}
private static final class StudentGroup {
private List<Student> student;
private int cost;
private int month;
}
private static final class Student {
String name;
int id;
}
推荐阅读
- python-requests - Airflow Long(时间)URL请求未收到响应
- java - “未解决的参考:http”Kotlin。为什么会这样?
- spring - Kotlin + Spring Boot - 将 TTL 添加到您的地图
- javascript - Webpack:动态依赖加载
- c# - XML 使用 SelectNodes 来获取具有空值子节点的节点
- sql - SQL 根据不同列中的值选择行
- sql - 根据其他列的最大值选择值
- python - 在同一进程中使用 Gstreamer 和 multiprocessing.Manager().Namespace() 时发生内存泄漏
- artifactory - Artifactory OSS:元数据服务日志项目更新错误
- spring - JPA:如何读取实体的特定字段?