简体   繁体   English

使用 PHP 将 JSON 数组发送到 Android Volley

[英]Sending JSON array using PHP to Android Volley

I am sending an array of data from MySQL query, and I am using json_encode to do that:我正在从 MySQL 查询发送一组数据,我正在使用 json_encode 来做到这一点:

public function getFriends($id){
$query = mysql_query(" SELECT uid, name, email
                        FROM users
                        RIGHT JOIN friendships 
                        ON friendid2 = uid")        or die (mysql_error());

$jsonData = '{"tag":"friends",error":"false",';
$jsonData .= '"friends":[';

while($row = mysql_fetch_array($query)){
    $i++;
    $id = $row["uid"];
    $name = $row["name"];
    $email = $row["email"];
    $jsonData .= '{"id":"'.$id.'","name":"'.$name.'","email":"'.$email.'"},';
}

$jsonData = chop($jsonData, ",");
$jsonData .= ']}';
echo json_encode($jsonData);

In the Android LogCat, when I'm creating JSON object I see this:在 Android LogCat 中,当我创建 JSON 对象时,我看到:

 org.json.JSONException: Value {"tag":"friends",error":"false","friends":[{"id":"4","name":"GrubyJohny2","email":"gruby@gmail.com"},{"id":"243000000","name":"Wariacik","email":"karol@wp.com"}]} of type java.lang.String cannot be converted to JSONObject

Can anyone tell me what am I doing wrong ?谁能告诉我我做错了什么? Becouse I searched bounch of toutorials and I think my json syntax is correct.因为我搜索了一堆教程,我认为我的 json 语法是正确的。

The way I am receiving message from server:我从服务器接收消息的方式:

private void getFriendships(final String id) {

    String tag_string_req = "req_friendships";
    pDialog.setMessage("Sending Request for list of friends");
    showDialog();
    final String TAG = "List of friends request";
    StringRequest strReq = new StringRequest(Request.Method.POST, AppConfig.URL_REGISTER, new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {
            Log.d(TAG, "Friendship request Response: " + response.toString());
            hideDialog();
            try {

                JSONObject jObj = new JSONObject(response); 
                boolean error = jObj.getBoolean("error");

                if (!error) {

                    Toast.makeText(getApplicationContext(), "Friends uploaded", Toast.LENGTH_LONG).show();

                } else {

                    String errorMsg = jObj.getString("error_msg");
                    Toast.makeText(getApplicationContext(), errorMsg, Toast.LENGTH_LONG).show();
                }
            } catch (JSONException e) {
                Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
                e.printStackTrace();
            }

        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e(TAG, "List of friends request Error: " + error.toString());

            Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
            hideDialog();

        }
    }) {

        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            params.put("tag", "friends");
            params.put("sender", id);

            return params;
        }

    };

    AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
"friends",error":"false"

The error key needs quotes on both sides. error键需要两边引号。

You can copy / paste the JSON in many free services, such as jsonlint.org that will parse your string for you and tell you if and where the errors are.您可以在许多免费服务中复制/粘贴 JSON,例如jsonlint.org ,它会为您解析您的字符串并告诉您是否存在错误以及错误在哪里。

As @Noman pointed out in the comments, you can also just build out the entirety of the data as a PHP array (and not just portions of it), and then simply json_encode all of it at the very end:正如@Noman 在评论中指出的那样,您也可以将整个数据构建为 PHP 数组(而不仅仅是其中的一部分),然后在最后简单地对所有数据进行json_encode

$jsonData = array(
    'tag' => 'friends',
    'error' => 'false',
    'friends' => array(),
);

while($row = mysql_fetch_array($query)) {
    $jsonData['friends'][] = array(
        'id'    => $row['uid'],
        'name'  => $row['name'],
        'email' => $row['email'],
    );
}

echo json_encode($jsonData);

Also, it should be noted that mysql_query as well as all mysql_* functions are now deprecated .另外,应该注意的是mysql_query以及所有mysql_*函数现在都已弃用 You should not write new code that uses these functions.您不应编写使用这些函数的新代码。 Instead you should learn to use either PDO or mysqli extensions for communicating with your database.相反,您应该学习使用PDOmysqli扩展与您的数据库进行通信。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM