ravi
ravi

Reputation: 6336

Count the id in JSON response with GSON

I am getting below JSON response from a REST service-

[
   {
      "id":"cls102",
      "name":"Class X",
      "students":[
         {
            "total-students":38,
            "present-students":35
         }
      ]
   },
   {
      "id":"cls202",
      "name":"Class XI",
      "students":[
         {
            "total-students":42,
            "present-students":38
         }
      ]
   }
]

My objective is to get the total number of element id. I created model class which looks like below-

public class ClassRoom {
    private String id;
    private String name;
    private Student[] students;
    // Getter and Setter are not put here
}

import com.google.gson.annotations.SerializedName;

public class Student {
    @SerializedName("total-students")
    private int totalStudents;
    @SerializedName("present-students")
    private int presentStudents;
    // Getter and Setter are not put here
}

Now my test class is calling Gson in following fashion-

Gson gson = new GsonBuilder().create();
ClassRoom agents = gson.fromJson(jsonRepsone, ClassRoom.class);

Now, how to proceed further?

Upvotes: 0

Views: 1677

Answers (1)

Rahul
Rahul

Reputation: 45070

You need to do something like this, because your JSON represents an array of ClassRoom objects.

Gson gson = new GsonBuilder().create();
ClassRoom[] agents = gson.fromJson(jsonRepsone, ClassRoom[].class);

//Gives the no. of ClassRoom objects, which corresponds to the no.of `id`s
System.out.println(agents.length);

Upvotes: 2

Related Questions