Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/392.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java JSONException正在尝试从JSON获取值_Java_Json - Fatal编程技术网

Java JSONException正在尝试从JSON获取值

Java JSONException正在尝试从JSON获取值,java,json,Java,Json,我试图用ant从api中解码java中的json响应,但我得到了一个错误 JSON是[{“order”:“test”,“tablenum”:1}] String url = "http://127.0.0.1:5000/order/1"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("GET"); con.setReq

我试图用ant从api中解码java中的json响应,但我得到了一个错误

JSON是
[{“order”:“test”,“tablenum”:1}]

String url = "http://127.0.0.1:5000/order/1";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");

con.setRequestProperty("Content-Type", "application/json");
int responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new 
InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();

while ((inputLine = in.readLine()) != null) {
    response.append(inputLine);
}

System.out.println(response);
String res = response.toString();
JSONObject jsonObject = new JSONObject(response);
JSONObject newJSON = jsonObject.getJSONObject("order"); // error is here
System.out.println(newJSON.toString());

错误告诉我线程“main”org.json.JSONException中存在异常:未找到JSONObject[“order”]。

错误原因是json实际上是一个数组。括号[]表示JSON中的对象数组。这意味着您的JSON是一个包含一个对象的数组。这将帮助您解决问题。您需要将JSON作为一个对象数组来处理。

查看JSON本身会很有帮助。请下次在发布代码之前多做一些工作来格式化代码。@FedericoklezCulloca这里刚刚出现,抱歉!一点帮助对我来说是巨大的!