gpt4 book ai didi

java - 使用 GSON 计算 JSON 响应中的 id

转载 作者:行者123 更新时间:2023-12-02 07:07:57 25 4
gpt4 key购买 nike

我从 REST 服务收到以下 JSON 响应 -

[
{
"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 -

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

现在,如何进一步进行?

最佳答案

您需要执行类似的操作,因为您的 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);

关于java - 使用 GSON 计算 JSON 响应中的 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15876554/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com