2

在我的一些与服务器通信并使用 http 获得响应的应用程序中,我使用 json 来格式化数据服务器端,当它到达设备时,我使用类似于我在 stackoverflow 上找到的代码:

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()); 
    }   
}
}

我尝试在找到此代码的页面上使用该解决方案。顺便说一句,这里是链接如何防止我的应用程序在使用 JSON 数据时意外崩溃,“强制关闭”,并改为处理异常?

我尝试使用在线验证器检查我的 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)
4

1 回答 1

2

在对字符串结果进行任何操作之前,您必须确保在执行空检查/或任何其他验证(例如检查它是否包含响应代码)之后进行解析。

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()); 
    }   
}
于 2012-06-10T01:42:10.403 回答