在我的一些应用程序,跟一个服务器,并使用http我使用JSON数据服务器端格式化,当它到达的设备我用类似这样的code,我的计算器发现了一些得到回应
私有类LoadData扩展的AsyncTask<太虚,太虚,字符串>{私人JSONArray jArray;私人字符串结果= NULL;私人InputStream为= NULL;。私有String entered_food_name = choice.getText()的toString()修剪();在preExecute保护无效(){}@覆盖保护字符串doInBackground(无效... PARAMS){尝试{ArrayList的<&的NameValuePair GT; namevaluepairs中=新的ArrayList<&的NameValuePair GT;();HttpClient的HttpClient的=新DefaultHttpClient();HttpPost httppost =新HttpPost(http://10.0.2.2/food.php);nameValuePairs.add(新BasicNameValuePair(名,entered_food_name));httppost.setEntity(新UrlEn codedFormEntity(namevaluepairs中,UTF-8));HTT presponse响应= httpclient.execute(httppost);HttpEntity实体= response.getEntity(); 是= entity.getContent(); //响应转换为字符串读者的BufferedReader =新的BufferedReader(新的InputStreamReader(是,UTF-8),8); StringBuilder的SB =新的StringBuilder(); 串线= NULL; 而((行= reader.readLine())!= NULL){ sb.append(线); } is.close(); 结果= sb.toString(); 。结果= result.replace('\\','\\'')修剪();}赶上(例外五){ Log.e(log_tag,连接+ e.toString());}返回结果;}@覆盖保护无效onPostExecute(字符串结果){尝试{ 串foodName =; int描述= 0; jArray =新JSONArray(结果); //此处若结果为空将发生exeption JSONObject的json_data = NULL; 的for(int i = 0; I< jArray.length();我++){ json_data = jArray.getJSONObject(ⅰ); foodName = json_data.getString(名称); 。 。 。 。 。 } 赶上(JSONException E){ ** //我可以做什么这里$ P $坠机pvent我的应用程序和 //使土司输入食品可用状态并没有???? ** Log.e(log_tag,parssing错误+ e.toString()); }}}
我试图用在哪里,我发现这个code页面上的解决方案。继承人顺便How我prevent我的应用程序意外崩溃,"强制关闭&QUOT ;,使用JSON数据时,并处理异常,而不是
我试图检查我的在线验证JSON响应并返回JSON是有效的。林想,当用户在一个贫穷的覆盖区域的连接立即中断或什么导致JSON被打破,导致即使我已经试过在我张贴在该链接的线程所建议的方法的JSON异常。所以,我希望能够验证JSON当它到达的电话,以便如果有效,我可以进行,如果不是我想尝试修复它,或者至少不会试图通过一个破碎和格式不正确的JSON阵列成引起该JSONException的方法之一。
在验证字符串我在得到响应,以确保其有效的JSON将是真棒任何提示。
编辑:有关问题的补充堆栈转储
org.json.JSONException:在类型的结果值null org.json.JSONObject $ 1不能被转换成JSONArray在org.json.JSON.typeMismatch(JSON.java:96)在org.json.JSONObject.getJSONArray(JSONObject.java:548)在it.cores.Activity $ GetM.doInBackground(Activity.java:1159)在it.cores.Activity $ GetM.doInBackground(Activity.java:1)在android.os.AsyncTask $ 2.call(AsyncTask.java:185)在java.util.concurrent.FutureTask中$ Sync.innerRun(FutureTask.java:306)在java.util.concurrent.FutureTask.run(FutureTask.java:138)在java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)在java.util.concurrent.ThreadPoolExecutor中的$ Worker.run(ThreadPoolExecutor.java:581)在java.lang.Thread.run(Thread.java:1019)
解决方案
您必须确保你做一个空检查/或任何其他验证如检查后做了解析,如果它包含响应code做任何之前在字符串结果操作。
保护无效onPostExecute(字符串结果){尝试{ 串foodName =; int描述= 0;如果(结果!= NULL)//做你进行结果验证{ jArray =新JSONArray(结果); //此处若结果为空将发生exeption JSONObject的json_data = NULL; 的for(int i = 0; I< jArray.length();我++){ json_data = jArray.getJSONObject(ⅰ); foodName = json_data.getString(名称); 。 。 。 。 。 } } 赶上(JSONException E){ ** //我可以做什么这里$ P $坠机pvent我的应用程序和 //使土司输入食品可用状态并没有???? ** Log.e(log_tag,parssing错误+ e.toString()); }}
In some of my applications that talk to a server and get a response using http I use json to format the data server side and when it gets to the device I use something similar to this code which I found on 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());
}
}
}
I tried to use the solution on the page where I found this code. heres the link by the way How do I prevent my app from crashing unexpectedly, "force close", when using JSON data, and handle the exception instead?
I tried checking my json response with online validators and the json returned is valid. Im thinking that when users are in a poor coverage area the connection momentarily breaks or something causes the json to be broken which causes a json exception even though I have tried the method suggested in the thread I posted in that link. So I would like to be able to validate the JSON when it gets to the phone so if its valid I can proceed and if not than I would like to try and fix it or at least not try to pass a broken and not properly formatted json array into one of the methods that causes the JSONException.
Any tips on validating the string I get in the response to make sure its valid JSON would be awesome.
Edit: added stack dump related to problem
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)
解决方案
You have to make sure you do the parsing after doing a null check/or any other validation like checking if it contains the response code before doing any operation on the String result.
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());
}
}