androidjsonandroid-volleyjsonobjectrequest

How to send json array as post request in volley?


I am using volley for json parsing. I want to send some data using POST to server side. I am trying to send .Now can any one tell me that how can i send filter array to server?

Following is my snippet code. i tried also Hashmap and Jsonobject. but getting this error.

Error :

org.json.JSONException: Value  at Data of type java.lang.String cannot be converted to JSONObject

Format

{
    "typeName": "MANUFACTURER",
    "typeId": 22,
    "cityId": 308,
    "sortBy": "productname",
    "sortOrder": "desc",
    "filter":[
                {
                    "filterId":101,
                    "typeName":"CAT_ID",

                     "filterId":102,
                    "typeName":"CAT_ID"
                }
             ]
}

For Code Check pastie

https://pastebin.com/u5qD8e2j


Solution

  • If you are having a problem in calling the API then this will help you.

    RequestQueue queue = Volley.newRequestQueue(this);
    JsonObjectRequest jobReq = new JsonObjectRequest(Request.Method.POST, url, jObject,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject jsonObject) {
    
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
    
                }
            });
    
    queue.add(jobReq);
    

    where jObject is the JSON data you want to send to the server.

    Implementation will be similar for JSONArray. Instead of JsonObjectRequest use JsonArrayRequest and send jArray instead of jObject.

    For creating json array just do a little tweak

    JSONArray array=new JSONArray();
    
    for(int i=0;i<filter_items.size();i++){
        JSONObject obj=new JSONObject();
        try {
            obj.put("filterId",filter_items.get(i));
            obj.put("typeName","CAT_ID");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        array.put(obj);
    }
    

    And finally add json array as below

    jsonParams.put("filter",array);
    

    In your case you are converting Json array to string