我试图学习春天,同时建立一个小项目,我遇到了一个问题。一切都正常工作,但我不知道如何使用Eclipse控制台中打印的API方法内容。
在我的控制器中,我拥有使用API的特定方法所需的所有信息。我使用"@GetMapping("/seasons")映射了这个URL,我使用了一个来自在线API的代码片段(带有键)。在视图文件夹(基本上是我保存seasons.jsp文件的地方)中,我试图从API的响应中检索数据。
这是API的响应:"{"get":"seasons","parameters":[],"errors":[],"results":10,"response":[2012,2013,2014,2015,2016,2017,2018,2019,2020,2021]}“
更新:
下面是一些参考代码:
@GetMapping("/seasons")
public String seasons(Model theModel) throws IOException, InterruptedException {
List<Integer> SeasonsList = new ArrayList<>();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api-formula-1.p.rapidapi.com/seasons"))
.header("x-rapidapi-host", "api-formula-1.p.rapidapi.com")
.header("x-rapidapi-key", "5a6f44fa10msh40be2be8d20bc5bp18a190jsnb4478dcbc8f1")
.method("GET", HttpRequest.BodyPublishers.noBody())
.build();
HttpResponse<String> response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
JSONObject seasonsObject = new JSONObject(response.body());
for(int i = 0; i < seasonsObject.length(); i++) {
JSONArray object = seasonsObject.getJSONArray("response");
for(int j = 0 ; i < object.length(); j++) {
SeasonsList.add(object.getInt(j));
}
System.out.println(object);
}
theModel.addAttribute("theSeasons", SeasonsList);
return "seasons";
}以及HTML文件:
<html xmlns:th ="http://www.thymeleaf.org">
<head>
<title>The Formula 1 Seasons are</title>
</head>
<body>
<p th:text ="'The seasons are: ' + ${theSeasons}"/>
</body>
</html>我想要展示的是“季节是:2012年,2013年,2014..etc”。
和我在控制台中发现了一个错误:"org.json.JSONException: JSONArray10 not“。
如果你需要我项目的任何细节,请告诉我。
发布于 2022-01-04 18:53:58
内环使用错误的循环变量并将j移动到数组的末尾:
// Don't do this
for (int j = 0 ; i < object.length(); j++) { // Comparing "i"; compare "j" instead
// Do this
for (int j = 0 ; j < object.length(); j++) {但是还不清楚为什么需要外部循环;您正在从已知的响应中提取已知的属性;没有理由使用外部循环AFAICT。
https://stackoverflow.com/questions/70568767
复制相似问题