在我的一些與服務器通信並使用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)
假設你在try catch塊中包裝JSONArray實例化,那麼你是不是保護你的應用程序免受強制關閉?所有你需要做的就是在使用之前檢查'jArray'是否爲空。通過用包含在字符串中的JSON數據實例化'JSONArray',將是一種驗證形式,否則將無法實例化。 – BDFun
返回的響應字符串不會爲空。正在發生的事情是,JSON有時會被打破。我無法重現我在崩潰回購中看到的錯誤,但從堆棧轉儲我可以看到它由org.json.JSONException引起:值爲null org.json.JSONObject $ 1類型的結果不能轉換爲JSONArray,試着抓。 –
從我讀過的所有東西中,當試圖解析破壞或格式不正確的json時,你會得到這個異常 –