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(); }
- 添加textView到拖放界面 – Android / Java
- java.io.EOFException使用ksoap2 lib libcore.io.Streams.readAsciiLine(Streams.java:203)
- 即使使用cancel方法也无法取消AsyncTask中的doInBackground进程
- Java中的快速傅里叶变换
- svg文件在android中呈现
- BitmapFactory.decodeFile返回null
- 我的应用程序适用于姜饼…… ICS和HC崩溃
- 如何在listview文件浏览器中删除条目和video文件?
- 主线程exception上的Android Bump Api网络