I've been trying to parse this but am getting the error : Exception in thread "main" java.util.concurrent.CompletionException: org.json.JSONException: A JSONArray text must start with '[' at 1 [character 2 line 1]
System.out.println("Which city would you like to find the weather for?");
try (Scanner s = new Scanner(System.in)) {
city = s.nextLine();
}
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder().uri(URI.create("http://api.openweathermap.org/data/2.5/weather?q=" city "&APPID=26aa1d90a24c98fad4beaac70ddbf274")).build();
client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse :: body)
//.thenAccept(System.out::println)
.thenApply(Main::parse)
.join();
}
public static String parse(String responseBody) {
JSONArray weather = new JSONArray(responseBody);
for (int i = 0; i < weather.length(); i ) {
JSONObject weatherObj = weather.getJSONObject(i);
int id = weatherObj.getInt("id");
// int userID = weatherObj.getInt("userId");
// String title = weatherObj.getString("title");
System.out.println(id " "/* title " " userID*/);
}
return null;
}
CodePudding user response:
since your url returns an object, not array, try
JSONObject weather = new JSONObject(responseBody);
CodePudding user response:
The API you are calling doesn't return an array but an object, so you have to deserialze to an object and not to an array. The data you are after is probably the weather
property of that response object.
JSONObject jsonResponse = new JSONObject(responseBody);
JSONArray weather = jsonResponse.getJSONArray("weather");