我一直在尝试解析这个,但得到错误:线程“main”java.util.concurrent中出现异常。完成异常:org.json.JSONException:JSONArray文本必须在1处以'['开头[第2行字符]
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;
}
2条答案
按热度按时间hyrbngr71#
因为你的url返回的是一个对象,而不是数组,
zour9fqk2#
您调用的API返回的不是数组而是对象,因此您必须反序列化为对象而不是数组。您要查找的数据可能是该响应对象的
weather
属性。