首页 > 解决方案 > 如何将 JSONObject 解析为整数列表?

问题描述

我有一个这样的json文件。

    {
        "student": [
            {
                "name": "takeru",
                "id": 23,
            },
            {
                "name": "george",
                "id": 43,
            },
            {
                "name": "hans",
                "id": 45,
            }
        ],
        "cost": 100,
        "month": 6
    }

我想要做的是将所有学生 ID 存储在 ArrayList 中?

标签: javajson

解决方案


首先,您的“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;
}

推荐阅读