2013-02-04 61 views
7

Possible Duplicate:
Determine whether JSON is a JSONObject or JSONArray如何檢查服務器的響應是JSONAobject還是JSONArray?

我有一個服務器默認返回一些JSONArray,但是當發生一些錯誤時,它返回錯誤代碼的JSONObject。我試圖解析JSON並檢查錯誤,我有一段代碼,檢查是否存在錯誤:

public static boolean checkForError(String jsonResponse) { 

    boolean status = false; 
    try { 

     JSONObject json = new JSONObject(jsonResponse); 

     if (json instanceof JSONObject) { 

      if(json.has("code")){ 
       int code = json.optInt("code"); 
       if(code==99){ 
        status = true; 
       } 
      } 
     } 

    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

    return status ; 
} 

,但我得到JSONException時jsonResponse是確定的,這是一個JSONArray(JSONArray不能轉換到的JSONObject)如何檢查jsonResponse是否會爲我提供JSONArray或JSONObject?

回答

15

使用JSONTokenerJSONTokener.nextValue()會給你一個Object,根據實例的不同,它可以動態轉換爲適當的類型。

Object json = new JSONTokener(jsonResponse).nextValue(); 
if(json instanceof JSONObject){ 
    JSONObject jsonObject = (JSONObject)json; 
    //further actions on jsonObjects 
    //... 
}else if (json instanceof JSONArray){ 
    JSONArray jsonArray = (JSONArray)json; 
    //further actions on jsonArray 
    //... 
} 
0

您正在嘗試將從服務器獲得的轉換字符串響應轉換爲導致異常的JSONObject。正如你所說,你會從服務器得到JSONArray,你試圖轉換成JSONArray。請參考link這將幫助您何時將字符串響應轉換爲JSONObjectJSONArray。如果響應隨[(左方括號)開始,然後將其轉換爲JsonArray如下

JSONArray ja = new JSONArray(jsonResponse); 

如果你的迴應{(開放的花括號)開始,然後將其轉換爲

JSONObject jo = new JSONObject(jsonResponse); 
相關問題