簡體   English   中英

如何正確讀取Java中的JSON數據?

[英]How to correctly read JSON data in Java?

我今天做了一些編碼,遇到了以下錯誤,我無法找到答案。

我有來自 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 數據不會是問題。

您正在將StringBuffer object 解析為JSONObject ,這會導致問題。 改為解析String響應:

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

通過此更改getJSONArray(myResponse)可以按預期工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM