Android:从JSON获取数据

时间:2014-08-26 16:02:48

标签: php android mysql json

我正在尝试从MySQL数据库获取数据到我的Android-App。我能够得到一个String,但如果我只想要一个数据,那就不太舒服......

我读过类似JSON的内容,并尝试了一些示例代码,但我总是收到错误消息,例如

"08-26 17:44:30.914: E/log_tag(9780): Error parsing data org.json.JSONException: No value for table1"

"08-26 17:45:52.403: E/log_tag(11220): Error parsing data org.json.JSONException: Value {"Role":"adminstrator","1":"0","age":"0","0":"adminstrator"} of type org.json.JSONObject cannot be converted to JSONArray"

那么我做错了什么?

PHP脚本:

<?php
$con=mysqli_connect(****);
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysqli_query($con,"SELECT Role, age FROM table1 where 
Username='$username' and Password='$password'");
$row = mysqli_fetch_array($result);
print json_encode($row);
mysqli_close($con);
?>

Android codesnippet

        String result = sb.toString();

      //parse json data
        try{
            //JSONObject object = new JSONObject(result);
            //JSONArray jArray = object.getJSONArray("table1");
                JSONArray jArray = new JSONArray(result);
                for(int i=0;i<jArray.length();i++){
                        JSONObject json_data = jArray.getJSONObject(i);
                        Log.i("log_tag","age: "+json_data.getInt("age")+
                                ", role: "+json_data.getString("Role")
                        );
                }
        }
        catch(JSONException e){
                Log.e("log_tag", "Error parsing data "+e.toString());
        }

结果内容:{"0":"adminstrator","Role":"adminstrator","1":"0","age":"0"}

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

你有JSONOBject而不是数组

try{
    JSONObject json_data = new JSONObject(result);
    Log.i("log_tag","age: " + json_data.getString("age") +
                  ", role: "+json_data.getString("Role"));
}
catch(JSONException e){
        Log.e("log_tag", "Error parsing data "+e.toString());
}

不要使用getInt,因为所有值都有引号,请改用getString


对于所有用户:

<强> PHP

$result = mysqli_query($con,"SELECT Role, age FROM table1 ");
$json = array();
while($row = mysqli_fetch_array($result)){
    $json[] = $row;
}
mysqli_close($con);
print json_encode($json);

<强> JAVA

try{
    JSONArray jArray = new JSONArray(result);
    for(int i=0;i<jArray.length();i++){
       JSONObject json_data = jArray.getJSONObject(i);
       Log.i("log_tag","age: " + json_data.getString("age") +
                      ", role: "+json_data.getString("Role"));
    }
}
catch(JSONException e){
        Log.e("log_tag", "Error parsing data "+e.toString());
}