[英]How to correctly read JSON data in Java?
I did some coding today and ran into the following error to which I am not able to find an answer.我今天做了一些编码,遇到了以下错误,我无法找到答案。
I have the following JSON data from an url:我有来自 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]]}
My goal is to now create an array or a list where the some data of the "targets" part is stored in. Eg: [891, 331, D-HUTH]我的目标是现在创建一个数组或列表,其中存储“目标”部分的一些数据。例如:[891, 331, D-HUTH]
I have the following code:我有以下代码:
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);
}
}
Now, both times I call...("targets"), I get an error saying that JSONObject["targets"] not found.
现在,我两次调用...(“targets”)时,都会收到一条错误消息,提示
JSONObject["targets"] not found.
. .
Why doesn't this work and what can I do to fix it?为什么这不起作用,我该怎么做才能解决它? I wrote the same program in Python and it works like a charm so the JSON data can't be the problem.
我在 Python 中编写了相同的程序,它就像一个魅力,所以 JSON 数据不会是问题。
You are parsing the StringBuffer
object to JSONObject
, which causes the problem.您正在将
StringBuffer
object 解析为JSONObject
,这会导致问题。 Parse the String
response instead:改为解析
String
响应:
String jsonresp = new String(response.toString());
// ...
JSONObject myResponse = new JSONObject(jsonresp);
With this change getJSONArray(myResponse)
works as expected.通过此更改
getJSONArray(myResponse)
可以按预期工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.