我收到JSON
服务的<{1}}响应 -
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
}
]
}
]
的总数。我创建了类似下面的模型类 -
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
现在,如何进一步处理?
答案 0 :(得分: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);