JSON对象无法转换为JSON数组

当我尝试从服务器转换以下JSON响应字符串时,我收到此错误。 我希望处理JSONObject或JSONArray,具体取决于服务器的响应,因为大多数时候它返回JSONArray。

来自服务器的JSON响应

jsonString = {"message":"No Results found!","status":"false"} 

Java代码如下

 try { JSONArray jsonArrayResponse = new JSONArray(jsonString); if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) { if(jsonArrayResponse != null && jsonArrayResponse.length() > 0) { getCancelPurchase(jsonArrayResponse.toString()); } } } catch(JSONException e) { e.printStackTrace(); } 

错误日志:

 org.json.JSONException: Value {"message":"No Results found!","status":"false"} of type org.json.JSONObject cannot be converted to JSONArray at org.json.JSON.typeMismatch(JSON.java:111) at org.json.JSONArray.(JSONArray.java:96) at org.json.JSONArray.(JSONArray.java:108) 

有谁能够帮我。

谢谢

根据您的评论回答1,您可以做到

 String data = "{ ... }"; Object json = new JSONTokener(data).nextValue(); if (json instanceof JSONObject) //you have an object else if (json instanceof JSONArray) //you have an array 

您的回复{"message":"No Results found!","status":"false"}不是数组。 这是一个对象。 在代码中使用JSONObject而不是JSONArray

提示:数组用方括号[]包裹,对象用大括号{}包裹。

我通过编写以下代码解决了这个问题[礼貌@Optional]

 String jsonString = "{\"message\":\"No Results found!\",\"status\":\"false\"}"; /* String jsonString = "[{\"prodictId\":\"P00001\",\"productName\":\"iPhone 6\"}," + "{\"prodictId\":\"P00002\",\"productName\":\"iPhone 6 Plus\"}," + "{\"prodictId\":\"P00003\",\"productName\":\"iPhone 7\"}]"; */ JSONArray jsonArrayResponse; JSONObject jsonObject; try { Object json = new JSONTokener(jsonString).nextValue(); if (json instanceof JSONObject) { jsonObject = new JSONObject(jsonString); if (jsonObject != null) { System.out.println(jsonObject.toString()); } } else if (json instanceof JSONArray) { jsonArrayResponse = new JSONArray(jsonString); if (jsonArrayResponse != null && jsonArrayResponse.length() > 0) { System.out.println(jsonArrayResponse.toString()); } } } catch (JSONException e) { e.printStackTrace(); }