0
votes

I am using Volley library to POST data to the server and I have a JSON response from server which is shown below.

Right now I can access "code" and status easily.

The problem is I'm unable to access "name" and other properties of "user". I have tried the following questions but they didn't help me and maybe that's because I am very new to JSON and android.

how to convert json object to string in android..?

How to convert json object into string in Android

JSONObject to String Android

How to convert this JSON object into a String array?

Im using volley library, here is the code:

StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {

@Override
    public void onResponse(String response) {
    try {

JSONObject jsonResponse = new JSONObject(response);
String code = jsonResponse.getString("status");

} catch (JSONException e) {
     e.printStackTrace();
}

}
},
new Response.ErrorListener() {
 @Override
 public void onErrorResponse(VolleyError error) {
      error.printStackTrace();
      }
    }
     ) {
                    @Override
                    protected Map<String, String> getParams() {
                        Map<String, String> params = new HashMap<>();
                        // the POST parameters:
                        params.put("name", userName);
                        params.put("email", userEmail);
                        params.put("password",userPass);
                        params.put("deviceIdentifier", deviceIdent);
                        params.put("deviceType", deviceI);

                        return params;
                    }
                };
                Volley.newRequestQueue(context).add(postRequest);

enter image description here

1

1 Answers

2
votes

You have to get the JSON objects first:

JSONObject response = new JSONObject(responseString);
if (response.has("data") {
   JSONObject data = response.getJSONObject("data");
   if (data.has("user") {
      JSONObject user = data.getJSONObject("user");
      String name = user.optString("name", "");
   }
}

Your response is built like this:

{ // JSONObject (lets call it response)
   "status": true, // boolean inside "response" JSONObject
   "code": 200, // int inside "response" JSONObject
   "data": { // JSONObject (lets call it data) inside "response" JSONObject
      [...], // Some more objects inside "data" JSONObject
      "user": { // JSONObject (lets call it user) inside "data" JSONObject
         [...], // Some more objects inside "user" JSONObject
         "name": "abc", // String inside "user" JSONObject
         [...], // Some more objects inside "user" JSONObject
      }
   }
}