我正在尝试从服务器检索一行。
我收到以下错误。
日志
E/log_tag(1948): connection success [sendernumber=9040307070]
E/log_tag(1948): result ?9545357470[{"TaskId":"1"},{"TaskId":"2"}]
E/log_tag(1948): Error parsing data org.json.JSONException: Value 9040307070 of type java.lang.Long cannot be converted to JSONArray
JSON代码
String result = null;
InputStream is = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.mydomainname.org/task/senttask.php");
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("sendernumber",name.toString()));
//nameValuePairs.add(new BasicNameValuePair("sendernumber","9595959595"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("log_tag", "connection success "+nameValuePairs);
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection "+e.toString());
Toast.makeText(getActivity(), "Connection fail", Toast.LENGTH_SHORT).show();
}
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,HTTP.UTF_8),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result=sb.toString();
Log.e("log_tag", "result "+result.toString());
}
catch(Exception e)
{
Log.e("log_tag", "Error converting result "+e.toString());
Toast.makeText(getActivity(), " Input reading fail", Toast.LENGTH_SHORT).show();
}
try
{
JSONArray jArray = new JSONArray(result);
String s="",s1,s2,s3,s4,s5;
Log.w("Lengh",""+jArray.length());
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
s=json_data.getString("TaskId");
Log.e("taskid from server","s");
}
}
catch(JSONException e)
{
Log.e("log_tag", "Error parsing data "+e.toString());
Toast.makeText(getActivity(), "JsonArray fail", Toast.LENGTH_SHORT).show();
}
服务器上的表格
TaskId int primary key
sendernumber varchar(100)
答案 0 :(得分:1)
如果您希望它简单有效,请使用JSONArray jArray = new JSONArray(result.substring(result.indexOf("[")));
代替JSONArray jArray = new JSONArray(result);
但是,您的网络服务似乎有些问题。它正在返回9545357470[{"TaskId":"1"},{"TaskId":"2"}]
,而且真的应该是[{"TaskId":"1"},{"TaskId":"2"}]
。因此,当您尝试创建json数组以将其作为响应发送时,我不确定究竟发生了什么,但最好的解决方案是修复它而不是此处的代码。