如何在Java中正确读取JSON数据?

问题描述 投票:0回答:1

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

我从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数据不会成为问题。

java json http url
1个回答
0
投票

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

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

进行此更改后,getJSONArray(myResponse)可以正常工作。

© www.soinside.com 2019 - 2024. All rights reserved.