0

I want to send post nested json parameters using volley library, please help me. I am able to send post parameters in simple json format, but in case of nested json, how to do that ?

ie. { "user": { "name": "Martin" "age": "20" } }

Here is my code:

    JSONObject mainJson  = new JSONObject();
    JSONObject userJson  = new JSONObject();
    try {
        userJson.put("first_name", firstname);
        userJson.put("last_name", lastname);
        userJson.put("email", email);
        userJson.put("role", "consumer");
        userJson.put("password", password);
        mainJson.put("user", userJson);
    } catch (JSONException e) {
        e.printStackTrace();
    }

     JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.POST, AppConfig.URL_SIGN_UP, mainJson, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            Log.d(TAG,response.toString());
            Log.d("TAG","====================== SUCCESS ========================");
            hideDialog();
            goToLoginPage();
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
            hideDialog();
            Log.d(TAG,error.toString());
        }
    }){
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type", "application/json");
            return headers;
        }
    };



    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(jsonRequest, TAG);

1 Answers1

3

Try this to make your JSON

private JSONObject getJsonObject(String name, String age) throws JSONException {
    JSONObject jsonObject = new JSONObject();
    JSONObject userJson = new JSONObject();
    userJson.put("name", name);
    userJson.put("age", age);
    jsonObject.put("user", userJson);
    return jsonObject;
}

And add to your Volley JSON request Object

try{
     JSONObject requestObject =new JSONObject();
     requestObject.put("yourParamName",getJsonObject("martin","20"));
}catch(JSONException e){

}
akhilesh0707
  • 6,709
  • 5
  • 44
  • 51