代码之家  ›  专栏  ›  技术社区  ›  Thunfische

如何将JSONObject解析为整数列表?

  •  1
  • Thunfische  · 技术社区  · 8 年前

    我有一个这样的JSON文件。

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

    我要做的是将所有学生ID存储在数组列表中?

    2 回复  |  直到 8 年前
        1
  •  1
  •   Marco Altieri PENG ZHU    8 年前

    首先,您的“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;
    }
    
        2
  •  0
  •   Quang Dat Pham    8 年前
    String jsonStr = "{ 'student': [ { 'name': 'takeru', 'id': 23, }, { 'name': 'george', 'id': 43, }, { 'name': 'hans', 'id': 45, } ], 'cost': 100, 'month': 6}";
    
    JSONObject jsonObj = new JSONOBject(jsonStr);
    JSONArray jsonArr = jsonObj.get("student");
    
    String name = "";
    int id = 0;
    for(JSONObject jo:jsonArr){
       name = jo.get("name");
       id = jo.get("id");
    }