arcegk
arcegk

Reputation: 1480

Nested JSON on Android with volley

I want to make a post request with volley to a REST API.

This is the code.

StringRequest postRequest = new StringRequest(Request.Method.POST, URL, 
            new Response.Listener<String>() 
            {
                @Override
                public void onResponse(String response) {
                    // response
                    Log.e("Response", response);
                }
            }
        ) {     
         @Override
            protected Map<String, String> getParams() 
            {  
                    Map<String, String>  params = new HashMap<String, String>();  
                    params.put("id_market", "-1");  
                    params.put("id_store", "1");
                    Log.e("OPE", params.toString() );
                    return params;  
            }




}

and i need something like this.

JSONParams={
"header": {
    "id_market": -1,
    "id_user_from": 1,
},
"detail": [
    {
        "id_product": 1,
        "id_market": -1,

    }
]

}

so, how can i make a nested JSON using volley?

Upvotes: 1

Views: 1354

Answers (1)

Simon Marquis
Simon Marquis

Reputation: 7526

From your code sample, you can use JsonObjectRequest instead of StringRequest:

final JSONObject jsonBody = new JSONObject("{\"header\": {\"id_market\": -1,\"id_user_from\": 1,},\"detail\": [{\"id_product\": 1,\"id_market\": -1,}]");
new JsonObjectRequest(URL, jsonBody, new Response.Listener<JSONObject>() { ... });

A working example will look like this:

    try {
        String url = "";
        JSONObject jsonRequest = new JSONObject("{\"header\": {\"id_market\": -1,\"id_user_from\": 1,},\"detail\": [{\"id_product\": 1,\"id_market\": -1,}]");
        new JsonObjectRequest(Request.Method.POST, url, jsonRequest, new Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                // Handle response
            }
        }, null /* Or handle error case */);
    } catch (JSONException e) {
        //Handle Excpetion
    }

Upvotes: 1

Related Questions