1

I have a json file like this.

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

What I want to do is storing all student id's in a ArrayList?

Thunfische
  • 1,107
  • 2
  • 15
  • 35
  • Possible duplicate of [How can I sort a JSONArray in JAVA](https://stackoverflow.com/questions/19543862/how-can-i-sort-a-jsonarray-in-java) – Ullas Hunka Jul 14 '18 at 12:40
  • @UllasHunka It is different because i need to parse "student" section first. Then i can get a jsonarray i guess. That's what I can not do either – Thunfische Jul 14 '18 at 12:49

2 Answers2

1

First of all, your "JSON file" is not a valid JSON. You have extra commas.

Assuming that your file is a valid JSON, you can use a library to parse JSON. I'd recommend Gson. Here's what the code could look like using 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;
}
Marco Altieri
  • 3,726
  • 2
  • 33
  • 47
Finn
  • 652
  • 7
  • 16
0
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");
}
Quang Dat Pham
  • 178
  • 1
  • 12