2017-10-05 127 views
-1

我收到此错误,当我试图从服务器转换下面的JSON响应字符串。我想根据服务器的响应来处理JSONObject或JSONArray,因为大部分时间它返回JSONArray。从服务器JSON对象无法转换为JSON数组

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.<init>(JSONArray.java:96) 
at org.json.JSONArray.<init>(JSONArray.java:108) 

任何人可以帮助我。

由于

+0

JsonArray串repsentation开头“[ “和jsonObject startswith”{“有更多的课程差异,请谷歌​​它 – nafas

回答

3

基于您的评论回答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 
+0

谢谢你明白我的观点。 –

2

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

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

+0

我也期待JSONArray的产品。我怎样才能同时处理JSONArray和JSONObject? –

+0

评论@nafas。 JsonArray字符串repsentation以“[”和jsonObject startswith“{”开头。我希望你能弄明白。 –

0

我通过写作解决这个问题,下面的代码[礼貌@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(); 
}