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

时间:2022-10-22 20:51:22

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":"grubyjohnny@gmail.com"},{"id":"243000000","name":"Wariacik","email":"karoltomczyk92@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.

谁能告诉我我做错了什么? Becouse我搜索了一些toutorials,我认为我的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);
}

1 个解决方案

#1


0  

"friends",error":"false"

The error key needs quotes on both sides.

错误键需要双方引用。

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. 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.

此外,应该注意,现在不推荐使用mysql_query以及所有mysql_ *函数。您不应该编写使用这些函数的新代码。相反,您应该学习使用PDO或mysqli扩展来与数据库进行通信。

#1


0  

"friends",error":"false"

The error key needs quotes on both sides.

错误键需要双方引用。

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. 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.

此外,应该注意,现在不推荐使用mysql_query以及所有mysql_ *函数。您不应该编写使用这些函数的新代码。相反,您应该学习使用PDO或mysqli扩展来与数据库进行通信。