代码之家  ›  专栏  ›  技术社区  ›  Taj Harris

JSONArray文本必须以“[”开头,位于1[字符2第1行]:需要帮助解析Json

  •  -1
  • Taj Harris  · 技术社区  · 3 年前

    我一直在尝试解析它,但得到了一个错误:线程“main”java中出现异常。util。同时发生的CompletionException:组织。json。JSONException:JSONArray文本必须以“[”开头,位于1[字符2第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;
    
    }
    
    2 回复  |  直到 3 年前
        1
  •  1
  •   Serge    3 年前

    由于url返回的是对象,而不是数组,请尝试

     JSONObject weather = new JSONObject(responseBody);
    
        2
  •  0
  •   derpirscher    3 年前

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

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