简体   繁体   中英

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:

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:

 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.

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.

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.

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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