0

我收到的服务JSON响应低于 -REST

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

我的目标是获得 element 的总数id。我创建了如下所示的模型类 -

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
}

现在我的测试班正在Gson按照以下方式调用-

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

现在,如何进一步进行?

4

1 回答 1

2

你需要做这样的事情,因为你的 JSON 代表一个ClassRoom对象数组。

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);
于 2013-04-08T10:22:27.150 回答