I'm trying to learn spring and at the same time build a small project and I encountered a problem. Everything works as it should, but I can't figure out how to make use of the API's method content that is printed in my Eclipse Console.
In my controller I have all the information required to use the specific method of the API. I mapped the URL using "@GetMapping("/seasons") and I'm using a code snippet from an online API(with key). And in the VIEW folder(basically where I keep the JSP files, example: seasons.jsp) I am trying to retrieve data from the response of the API.
This is the response of the API: "{"get":"seasons","parameters":[],"errors":[],"results":10,"response":[2012,2013,2014,2015,2016,2017,2018,2019,2020,2021]}
"
UPDATE:
Here is some code for refference:
@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";
}
And the HTML file:
<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>
The thing that I want is to show "The seasons are : 2012, 2013, 2014..etc.
And I get an error in console : "org.json.JSONException: JSONArray[10] not found."
Please let me know if you need any detail from my project.
CodePudding user response:
Your inner loop uses the wrong loop variable and moves j
past the end of the array:
// 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 ) {
It's not clear why there needs to be an outer loop, though; you're pulling a known property from a known response; there's no reason for the outer loop AFAICT.