结果无法转换为JSON数组

时间:2012-05-07 20:32:52

标签: php android json

我正在尝试从我的Android应用程序中的MYSQL数据库返回数据,但是当我运行应用程序时,返回的结果无法转换为JSON数组“发生异常,说JSONException:类型java.lang.String的值不能是转换为JSONArray“

我确保php脚本以JSON格式返回数据,并且在解析之前结果为null,它保存返回的数据。为什么会发生这种异常以及如何解决它?请帮帮我

这是我的代码:

       private class LoadData extends AsyncTask<Void, Void, String> { 

 private String result = "";
 private InputStream is = null;

 private ProgressDialog progressDialog;



protected void onPreExecute() 
{
       this.progressDialog = ProgressDialog.show(AddFood.this, "","Loading......");  
}

@Override
            protected String  doInBackground(Void... params)
            {
                 MealActivity.foodList = new ArrayList<ItemInList>();     

   try
   {
          ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
         nameValuePairs.add(new BasicNameValuePair("Name",entered_food_Name));
         HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://10.0.2.2/food.php");
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));
       HttpResponse response = httpclient.execute(httppost);
       HttpEntity entity = response.getEntity();
      is = entity.getContent();
       }
   catch(Exception e)
    {
        Log.e("log_tag", "Error in http connection "+e.toString());
      }
//convert response to string
   try{
        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 + "\n");
        }
        is.close();
        result=sb.toString();
        }
        catch(Exception e){
        Log.e("log_tag", "Error converting result "+e.toString());
        }
   Log.e("log_tag",result+ "result");
    return result;
    }


@Override
protected void onPostExecute(String  result) 
                   {
                              this.progressDialog.dismiss();

    try{
         Log.e("log_tag", " result before parsing " + result);

         String foodName="";
         int Description=0;

         JSONArray jArray = new JSONArray(result);
            JSONObject json_data=null;
            for(int i=0;i<jArray.length();i++)
            {
                json_data = jArray.getJSONObject(i);

             foodName=json_data.getString("Name");
             Description=json_data.getInt("Calories");              
             item.setName(foodName);
             item.setDescription(Description);
             item.setSelected(false);
             MealActivity.foodList.add(item);   
                                                             }

                                                                 }
            catch(JSONException e){
                Log.e("log_tag", "parssing error " + e.toString());
            }   

    }}

这是php脚本:

<?php

 $con1=mysql_connect("localhost" , "user","pass" ) ;

 mysql_select_db("MYDB");
 mysql_query("SET NAMES utf8"); 

 $sql=mysql_query("select  Name,Calories  from food where Name LIKE      '%".$_REQUEST['Name']."%' ");

while($row=mysql_fetch_assoc($sql))
$output[]=$row;
$data =json_encode($output);
print($data);
mysql_close();

  ?>

返回数据

  E/log_tag(491):  result before parsing             [{"Name":"\u0627\u0641\u0648\u0643\u0627\u062f\u0648","Calories":"160"}]

2 个答案:

答案 0 :(得分:2)

您可以使用以下代码使代码看起来更简单:

String jsonStr = EntityUtils.toString(entity, HTTP.UTF_8);

从实体获取String。

看起来很可疑是'解析'和左大括号之间的这个长差距:'[',看起来里面有一些控制字符。以下是一些提示:

  1. 确保使用ASCII编码编写php文件,可能是HTML编辑器在.php文件的开头添加了BOM标记。
  2. 确保外面没有字符&lt;?php和?&gt;标记
  3. 要验证结果字符串中有哪些错误字符,请将它们输出为以字节为单位的日志,UTF-8 BOM如下所示:0xEF,0xBB,0xBF
  4. 否则你的json解析看起来很好

答案 1 :(得分:1)

$sql=mysql_query("select  Name as name,Calories as cal  from food where Name LIKE      '%".$_REQUEST['Name']."%' ");

几乎没有变化你的问题就会解决。

while($row=mysql_fetch_assoc($sql))

$name=$row['name'];

$cal=$row['cal'];

$data1 =json_encode($name);

$data2=json_encode($cal);

print($data1);
print($data2);