从mysql编写适当的JSON结构

时间:2012-02-21 08:31:20

标签: php android mysql json

我正在尝试从mysql中检索数据,然后在android listview上显示它。 我曾尝试过一些教程,但我不知道如何编写一个可以将数据从mysql发送到android的正确代码。

这是我为测试而做的JSON结构。

{
"users": [
    {
            "id": "001",
            "name": "John",
            "email": "john@gmail.com",
            "gender" : "male"
    },
    {
            "id": "002",
            "name": "Mary",
            "email": "mary@gmail.com",
            "gender" : "female"
    } 
]}

如果所有这些数据都在mysql数据库上,表格为“USERS”并包含“ID”,“NAME”,“EMAIL”,“GENDER”。如何写一个JSON用mysql ??

这是Android中用于显示数据的代码。

// JSON Node names
private static final String TAG_USERS = "users";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_GENDER = "gender";
JSONArray users = null;
.
.
.
try {
        // Getting Array of Users
        contacts = json.getJSONArray(TAG_USERS);

        // looping through All Users
        for(int i = 0; i < users.length(); i++){
            JSONObject c = users.getJSONObject(i);

            // Storing each json item in variable
            String id = c.getString(TAG_ID);
            String name = c.getString(TAG_NAME);
            String email = c.getString(TAG_EMAIL);
            String gender = c.getString(TAG_GENDER);

2 个答案:

答案 0 :(得分:4)

您必须使用 json_encode() 功能。

// MySQL query, maybe you already have something similar
$query = 'SELECT * FROM users LIMIT 5';
$res = mysql_query($query);

// Push all records from the database into a single array
$users = array();
$users['users'] = array(); // Your "users" key for JSON
while ($user = mysql_fetch_assoc($res)) {
    $users['users'][] = $user;
}

// Encode and output that array as JSON, then end the script
echo json_encode($users);
exit();

答案 1 :(得分:3)

使用PHP的json_encode()函数将值数组转换为JSON字符串