2017-10-05 42 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(); 
}