我正在嘗試學習spring,同時構建一個小專案,我遇到了一個問題。一切正常,但我不知道如何使用在我的 Eclipse 控制臺中列印的 API 方法內容。
在我的控制器中,我擁有使用 API 的特定方法所需的所有資訊。我使用“@GetMapping("/seasons")映射了 URL,并且我使用了來自在線 API 的代碼片段(帶有密鑰)。在 VIEW 檔案夾中(基本上我保存 JSP 檔案的位置,例如: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..等。
我在控制臺中收到錯誤:“org.json.JSONException: JSONArray[10] not found。”
如果您需要我的專案的任何細節,請告訴我。
uj5u.com熱心網友回復:
您的內部回圈使用錯誤的回圈變數并移動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://www.uj5u.com/gongcheng/407047.html
標籤:
