2015-12-07 107 views
1

我的Volley請求可以返回爲JSONArray(有效)或JSONObject(錯誤消息),並且爲了正確顯示錯誤響應,我想將失敗的JSONArray字符串解析爲JSONObject。看起來JSONException對象包裝了原始文本。是否有可能得到只是失敗的文本,以解析它不同?從Android獲取JSON字符串JSONException

例子:

org.json.JSONException: Value {"error":"User has not signed up to be a customer"} of type org.json.JSONObject cannot be converted to JSONArray 

,我希望得到公正的JSON字符串組成部分,因爲它是一個有效的JSONObject。

+0

您的錯誤是否與'HTTP 200'一起出現,還是您獲得了特定的狀態碼? – Androiderson

回答

1

因爲你的反應要麼是JSONArray(有效)或JSONObject的(錯誤信息),所以你可以參考下面的代碼:

// Check the response if it is JSONObject or JSONArray 
Object json = new JSONTokener(response).nextValue(); 
if (json instanceof JSONObject) { 
    // do something... 
} else if (json instanceof JSONArray) { 
    // do something... 
} 

希望它能幫助!

+1

這指出我在正確的方向,謝謝!我添加了一個答案,看看我做了什麼。 – MechEngineer

0

我不認爲實際上可以從JSONException中檢索JSON字符串,所以最終我從BNK得到了答案,並且在這種情況下做了可能最簡單的解決方案。

這個技巧似乎是要接收一個StringRequest,並且一旦知道有一個有效的字符串響應,就執行JSON處理。以下是我的項目中的外觀。

StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() { 
     @Override 
     public void onResponse(String response) { 
      activity.hideProgress(); 

      try { 
       Object json = new JSONTokener(response).nextValue(); 
       if (json instanceof JSONArray) { 
        // an array is a valid result 
        dataModel.loadData((JSONArray)json); 
       } else if (json instanceof JSONObject) { 
        // this is an error 
        showErrorMessageIfFound((JSONObject)json); 
       } 
      } catch (JSONException error) { 
       error.printStackTrace(); 
      } 

      refreshTable(); 
     } 
    }, new Response.ErrorListener() { 
     @Override 
     public void onErrorResponse(VolleyError error) { 
      activity.hideProgress(); 
      showVolleyError(error); 
      // check for a JSONObject parse error 
     } 
    }); 

首先有一個StringRequest來檢索響應。錯誤響應顯示我的自定義錯誤處理器的錯誤。成功響應解析JSON並使用最終結果向最終用戶顯示正確的內容。