How to send nested json as post in android

Viewed 153

im using android valley library, currently im only able to post simple json, im struggling in posting nested json format like this :

{
"user": {
    "email": "digest@example.com",
    "password": "thedigest123" 

it looks like i didnt know how to format the nested json for this case, could you help me?

here's my java class that i used to connect my web api

public void login(String email, String password) {
    String url = BASE_URL + "api/session";
    JSONObject jsonObject = new JSONObject();

    try {
        jsonObject.put("email", email);
        jsonObject.put("password", password);

        Response.Listener<JSONObject> successListener = new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                Toast.makeText(mApplication, "Success", Toast.LENGTH_SHORT).show();
            }
        };

        Response.ErrorListener errorListener = new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(mApplication, "Error", Toast.LENGTH_SHORT).show();
            }
        };

        JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, jsonObject, successListener, errorListener);
        mRequestQueue.add(request);
    }

    catch (JSONException e) {
        Toast.makeText(mApplication, "JSON exception", Toast.LENGTH_SHORT).show();
    }

}
2 Answers
  1. Create dto classes for your request body:

    public class UserRequestDTO{
        private UserDto user;
        //getters, setters
    }
    public class UserDto{
        private String email;
        private String password;
    }
    
  1. Convert it to json string using Gson lib:

    public static String stringify(Object obj) {
         Gson gson = new Gson();
         String jsonString = gson.toJson(obj);
         return jsonString;
    }
    

Then convert it to StringEntity with new StringEntity(stringify(new UserRequestDto(/*params*/), "UTF-8"); or to JSONObject with new JSONObject(stringify(new UserRequestDto(/*params*/));, and use it in your request.

If you don't want the overhead of Gson or creating classes (unless you intend to have more complex objects) You can simply do:

JSONObject userJsonObject = new JSONObject("{ \"user\": {\"email\": \"" + email + "\", \"password\": \"" + password + "\" } }");
Related