gson JSONArray文本必须在1处以"[“开头[字符2行1]:需要解析Json的帮助

whhtz7ly  于 2022-11-06  发布在  其他
关注(0)|答案(2)|浏览(244)

我一直在尝试解析这个,但得到错误:线程“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;

}
hyrbngr7

hyrbngr71#

因为你的url返回的是一个对象,而不是数组,

JSONObject weather = new JSONObject(responseBody);
zour9fqk

zour9fqk2#

您调用的API返回的不是数组而是对象,因此您必须反序列化为对象而不是数组。您要查找的数据可能是该响应对象的weather属性。

JSONObject jsonResponse = new JSONObject(responseBody);
JSONArray weather = jsonResponse.getJSONArray("weather");

相关问题