无法解析MySQL数据库中的JSON数据

时间:2012-08-15 13:47:17

标签: android mysql json getjson

我正在开发一个Android应用程序,它要求我连接到mysql数据库并从中检索信息。我使用PHP脚本连接到服务器并查询它,然后以json格式输出结果:     

if(!mysql_connect($mysql_host,$mysql_user,$mysql_pass) || !mysql_select_db($mysql_db)){
die($conn_error);
}



$q=mysql_query("SELECT * FROM food");

  while($e=mysql_fetch_assoc($q))

          $output[]=$e;

       print(json_encode($output));

mysql_close();




?>

这是我的java代码,它使用HttpGet获取数据并将其转换为字符串。然后它意味着解析数据并在屏幕上显示它。

public class HttpExample extends Activity {

TextView httpStuff;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.httpex);
    httpStuff = (TextView) findViewById(R.id.tvHttp);

    GetMethodEx test = new GetMethodEx();
    String returned;
    try {
        returned = test.getInternetData();
        httpStuff.setText(returned);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

public class GetMethodEx {

    public String getInternetData() throws Exception {

        BufferedReader in = null;
        String data = "";
        String returnString = null;

        // httpGet

        try {

            HttpClient client = new DefaultHttpClient();
            URI website = new URI("http://10.0.2.2/connect.php");
            HttpGet request = new HttpGet();
            request.setURI(website);
            HttpResponse response = client.execute(request);
            in = new BufferedReader(new InputStreamReader(response
                    .getEntity().getContent()));
            StringBuffer sb = new StringBuffer("");
            String l = "";
            String nl = System.getProperty("line.separator");

            while ((l = in.readLine()) != null) {
                sb.append(l + nl);
            }
            in.close();
            data = sb.toString();
            // return data;
        } catch (Exception e) {
            Log.e("log_tag", "Error converting result " + e.toString());
        }
        // parse json data
        try {
            JSONArray jArray = new JSONArray(data);
            for (int i = 0; i < jArray.length(); i++) {
                JSONObject json_data = jArray.getJSONObject(i);
                Log.i("log_tag", "Foodname: " + json_data.getString("food"));
                // Get an output to the screen
                returnString += "\n\t" + jArray.getJSONObject(i);
            }
        } catch (JSONException e) {
            Log.e("log_tag", "Error parsing data " + e.toString());
        }
        return returnString;

    }

}

}

除了解析数据外,它正在做我想做的一切。当我只想要食物名称时,它只是在屏幕上显示数据库的全部内容。任何人都可以帮忙吗?谢谢

编辑:这是我的PHP脚本

的json输出的截图

enter image description here

1 个答案:

答案 0 :(得分:2)

尝试

returnString += "Foodname: " + json_data.getString("food") + "\n";

而不是

returnString += "\n\t" + jArray.getJSONObject(i);

我认为这只会显示食物的名称。我现在无法测试它,因为我正在手机上写这个。