gpt4 book ai didi

java - 如何使用 GSON 获取 JSON 数据

转载 作者:行者123 更新时间:2023-11-29 07:26:14 28 4
gpt4 key购买 nike

这可能以前有人问过,但我不知道我的问题的术语,因此不知道要查找什么。

我正在使用 GSON 和 Java 尝试从已解析的 JSONElement 中获取信息。

Java代码:

    JsonParser parser = new JsonParser();

String url = "https://chapel-logs.herokuapp.com/attendance";

URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();

// optional default is GET
con.setRequestMethod("GET");

//add request header
con.setRequestProperty("Accept", "application/json");

int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);

BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();

while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}

in.close();

//print result
JsonElement element = parser.parse(response.toString());

if (element.isJsonObject()) {
JsonObject albums = element.getAsJsonObject();
System.out.println(albums.get("students")); //prints out data in students
System.out.println(albums.get("students.LastChapelAttended")); //error
}

我的 JSON:

{"students":[{"LastChapelAttended":{"Loc":"","Chapel":"WhyChapel","Year":2018,"Month":9,"Day":6,"Hour":15,"Min":14,"Sec":28},"StudNum":"F02660934","Attendance":17},{"LastChapelAttended":{"Loc":"","Chapel":"WhyChapel","Year":2018,"Month":9,"Day":5,"Hour":19,"Min":49,"Sec":11},"StudNum":"002660934","Attendance":2},{"LastChapelAttended":{"Loc":"","Chapel":"WhyChapel","Year":2018,"Month":9,"Day":4,"Hour":20,"Min":35,"Sec":57},"StudNum":"002643472","Attendance":2},{"LastChapelAttended":{"Loc":"","Chapel":"WhyChapel","Year":2018,"Month":9,"Day":7,"Hour":5,"Min":34,"Sec":54},"StudNum":"002664906","Attendance":1}]}

我要获取的数据是:LastChapelAttended,但是 LastChapelAttendedstudents 中。在 JavaScript 中,如果有帮助,与我正在尝试的等效的是 students.LastChapelAttended

提前致谢!

最佳答案

JsonObject jObj=(JsonObject)albums.get("students").getAsJsonArray().get(0);
System.out.println(jObj.get("LastChapelAttended"));

将其作为 JsonArray 获取,然后遍历数组以获取 LastChapelAttended。

关于java - 如何使用 GSON 获取 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52216443/

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