2012-06-10 114 views
2

在我的一些與服務器通信並使用http獲取響應的應用程序中,我使用json格式化數據服務器端以及當它到達設備我使用類似於我在代碼中找到的代碼:Android - 從服務器獲取響應時驗證JSON以避免出現JSONException

private class LoadData extends AsyncTask<Void, Void, String> 
{ 
private JSONArray jArray; 
private String result = null; 
private InputStream is = null; 
private String entered_food_name=choice.getText().toString().trim(); 
protected void onPreExecute() 
{ 
} 

@Override 
protected String doInBackground(Void... params) 
{ 
try { 
ArrayList<NameValuePair> nameValuePairs = new   ArrayList<NameValuePair>(); 
HttpClient httpclient = new DefaultHttpClient(); 
HttpPost httppost = new HttpPost("http://10.0.2.2/food.php"); 
nameValuePairs.add(new BasicNameValuePair("Name",entered_food_name)); 
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8")); 
HttpResponse response = httpclient.execute(httppost); 

HttpEntity entity = response.getEntity(); 
is = entity.getContent(); 

    //convert response to string 

BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),8); 
    StringBuilder sb = new StringBuilder(); 
    String line = null; 
    while ((line = reader.readLine()) != null) { 
     sb.append(line); 
    } 

    is.close(); 


    result =sb.toString(); 
    result = result.replace('\"', '\'').trim(); 

} 
catch(Exception e){ 
    Log.e("log_tag", " connection" + e.toString());      
} 


return result; 

} 

@Override 
protected void onPostExecute(String result) 
{ 
try{ 

    String foodName=""; 
    int Description=0; 

    jArray = new JSONArray(result); // here if the result is null an exeption will occur 
    JSONObject json_data = null; 

    for (int i = 0; i < jArray.length(); i++) { 
     json_data = jArray.getJSONObject(i); 
     foodName=json_data.getString("Name"); 
     . 
     . 
     . 
     . 
     . 
    } 
    catch(JSONException e){ 
     **// what i can do here to prevent my app from crash and 
     // make toast " the entered food isnot available " ????** 
     Log.e("log_tag", "parssing error " + e.toString()); 
    } 
} 
} 

我試圖在我找到此代碼的頁面上使用該解決方案。繼承人的方式鏈接How do I prevent my app from crashing unexpectedly, "force close", when using JSON data, and handle the exception instead?

我試着檢查我的JSON響應與在線驗證和JSON返回是有效的。我認爲,當用戶處於較差的覆蓋區域時,連接暫時中斷或者導致json被破壞,從而導致json異常,即使我嘗試了在該鏈接中發佈的線程中建議的方法。所以我希望能夠驗證JSON到手機的時候,所以如果它的有效的我可以繼續,如果不是,我想嘗試修復它,或者至少不要嘗試通過一個破碎的格式不正確的JSON數組放入導致JSONException的其中一個方法中。

驗證字符串的任何提示我在響應中獲取以確保其有效的JSON會很棒。

編輯:有關問題的補充堆棧轉儲

org.json.JSONException: Value null at results of type org.json.JSONObject$1 cannot be  converted to JSONArray 
at org.json.JSON.typeMismatch(JSON.java:96) 
at org.json.JSONObject.getJSONArray(JSONObject.java:548) 
at it.cores.Activity$GetM.doInBackground(Activity.java:1159) 
at it.cores.Activity$GetM.doInBackground(Activity.java:1) 
at android.os.AsyncTask$2.call(AsyncTask.java:185) 
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306) 
at java.util.concurrent.FutureTask.run(FutureTask.java:138) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581) 
at java.lang.Thread.run(Thread.java:1019) 
+0

假設你在try catch塊中包裝JSONArray實例化,那麼你是不是保護你的應用程序免受強制關閉?所有你需要做的就是在使用之前檢查'jArray'是否爲空。通過用包含在字符串中的JSON數據實例化'JSONArray',將是一種驗證形式,否則將無法實例化。 – BDFun

+0

返回的響應字符串不會爲空。正在發生的事情是,JSON有時會被打破。我無法重現我在崩潰回購中看到的錯誤,但從堆棧轉儲我可以看到它由org.json.JSONException引起:值爲null org.json.JSONObject $ 1類型的結果不能轉換爲JSONArray,試着抓。 –

+0

從我讀過的所有東西中,當試圖解析破壞或格式不正確的json時,你會得到這個異常 –

回答

2

你必須確保你做一個空檢查/或任何其他驗證如檢查後做了解析,如果它包含做任何操作之前響應代碼在String結果上。

protected void onPostExecute(String result) 
{ 
try{ 

    String foodName=""; 
    int Description=0; 

if(result!=null)//Do your validation for result 

{ 
    jArray = new JSONArray(result); // here if the result is null an exeption will occur 
    JSONObject json_data = null; 

    for (int i = 0; i < jArray.length(); i++) { 
     json_data = jArray.getJSONObject(i); 
     foodName=json_data.getString("Name"); 
     . 
     . 
     . 
     . 
     . 
    } 
} 
    catch(JSONException e){ 
     **// what i can do here to prevent my app from crash and 
     // make toast " the entered food isnot available " ????** 
     Log.e("log_tag", "parssing error " + e.toString()); 
    } 
} 
+0

是的,目前我已經做了,但我想積極地處理個案當json將其發送到設備並且其格式不正確時。我無法重現一些人似乎「在野外」的錯誤。你知道嗎?無論如何,我可以驗證我的JSON後,它來到設備和結果字符串不爲空。 –

+1

如果你可以檢查你從服務器得到的響應代碼(如成功的200個),也會有空檢查 –

+0

這將是一件好事。問題不在於服務器的響應,對我而言,響應正如預期的那樣。這個問題似乎是在網絡條件不佳的情況下json變得破碎了一些如何,因爲它不再格式正確我得到JSONException。 –

相關問題