【问题标题】:How to correctly read JSON data in Java?如何正确读取 Java 中的 JSON 数据?
【发布时间】:2020-09-23 22:55:22
【问题描述】:

我今天做了一些编码,遇到了以下错误,我无法找到答案。

我有以下来自 url 的 JSON 数据:

{"server_stats": { "n_mobile": 1200, "n_tracking": 1200, "n_disclose_id": 717, "n_stealth": 6, "n_static": 21, "n_sos": 2 },"targets": [ ["icao:3E0965", 3, "2020-06-04T19:43:48Z", 891, 49.06455, 10.414433, 631.9, 0, 3, 50, 331, -4.2, -3, 0, 1, 0, "AIRS44806", ["D-HUTH", "ADA", "-", "-"], 100, 0, 0]]}

我现在的目标是创建一个数组或列表,其中存储“目标”部分的一些数据。 例如:[891, 331, D-HUTH]

我有以下代码:

public class webscraper {
    public static void main(String[] args) {
        try {
            webscraper.call_me();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void call_me() throws Exception{
        String url = "https://ktrax.kisstech.ch/backend/tracking?db=aviation&sw_lat=40.97765930663377&sw_lon=-26.280096606906117&ne_lat=43.01854550507729&ne_lon=-23.407171802218617&ktrax_id=icao%3a3E0965&format=json";
        URL obj = new URL(url);

        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        //Checking for reponse code of GET Method
        con.setRequestMethod("GET");
        int responseCode = con.getResponseCode();
        System.out.println("Response Code : " +responseCode);

        //Reading Data
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        //outputting the data as a string to test if it works
        String jsonresp = new String(response.toString());
        System.out.println(jsonresp);

        //creating a JSONObject
        JSONObject myResponse = new JSONObject(response);

        //trying to either print the target using JSONArray or string
        JSONArray test = myResponse.getJSONArray("targets");
        System.out.println(test);
        String resp = myResponse.getJSONObject("targets").toString();
        System.out.println(resp);
    }
}

现在,我两次调用 ...("targets") 时都会收到错误消息,指出 JSONObject["targets"] not found.

为什么这不起作用,我可以做些什么来解决它?我用 Python 编写了相同的程序,它的工作原理非常棒,因此 JSON 数据不会是问题。

【问题讨论】:

  • 在你的例子中targets实际上是一个数组,你为什么尝试像一个对象一样检索它?
  • 使用 Spring RestTemplate 等客户端库,您的整个方法可以替换为 restTemplate.getForEntity(url, Target.class)

标签: java json http url


【解决方案1】:

您正在将 StringBuffer 对象解析为 JSONObject,这会导致问题。改为解析 String 响应:

String jsonresp = new String(response.toString());
// ...
JSONObject myResponse = new JSONObject(jsonresp);

通过此更改 getJSONArray(myResponse) 可以按预期工作。

【讨论】:

  • OP 有new JSONObject(response),只需将其更改为new JSONObject(jsonresp)new JSONObject(response.toString())。请注意,JSONObject ctor 需要 Object,这是我猜的问题。
  • 稍后会再次失败,因为 OP 尝试将数组视为对象,但出现异常 Exception in thread "main" org.json.JSONException: JSONObject["targets"] is not a JSONObject. at org.json.JSONObject.wrongValueFormatException(JSONObject.java:2590)
  • @AlexRudenko,是的。这正是我在答案中写道getJSONArray() 会起作用的原因;另一个没有。
  • @Olli 谢谢!这解决了问题。现在,开始进一步探索 java 和 json 对象:)
猜你喜欢
  • 2020-08-02
  • 2018-05-23
  • 2015-07-25
  • 2023-03-26
  • 1970-01-01
  • 2021-11-04
  • 2016-07-19
  • 2017-11-26
  • 1970-01-01
相关资源
最近更新 更多