How to send json array as post request in volley?
Asked Answered
C

6

13

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

Chippy answered 26/9, 2017 at 9:31 Comment(1)
see hereUngainly
Y
15

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

Yate answered 26/9, 2017 at 9:45 Comment(12)
hey kunu neither map nor jsonobject is working properlyChippy
What do you mean by not working properly? Because if you implement correctly it's gonna work.Show your implementation and error.Yate
Use Postman to check your responseYate
bro did you check error? and response is false..cuz of errorChippy
And though your request format is correct it depends on what your server expects to receive. That's why I am asking you to check in Postman then cross check with your code.Yate
Do you want send a Json array or a json object?Yate
Same issue bro..no change..and in my log i am getting this..for request {"typeName":"MANUFACTURER","typeId":"22","cityId":"308","sortBy":"productname","sortOrder":"desc","filter":"[{\"filterId\":\"128\",\"typeName\":\"CAT_ID\"}]"}Chippy
Check again my answerYate
Do not convert json array to string just add it in Json object as it is.Yate
incredible answer bro..accepted ..for bounty its not allowing for 24 hoursChippy
Gives me wrong 2nd type argument, required String found JSONArray error. When I convert jsonArray.toString() it gives me cast to Array failed errorAlexio
@BugsBuggy Can you post your question and redirection link here?Yate
R
7

I used below code to post JSONArray to volley. You have to use JsonArrayRequest and pass the JSON Array directly without adding it to any JSONObject. Also keep in mind to Override the "parseNetworkResponse" method to convert the response to JSONArray again as The ResponseListner for JsonArrayRequest expects a type of JSONArray

    String URL = "www.myposturl.com/data";

    RequestQueue queue = Volley.newRequestQueue(this);

    //Create json array for filter
    JSONArray array = new JSONArray();

    //Create json objects for two filter Ids
    JSONObject jsonParam = new JSONObject();
    JSONObject jsonParam1 = new JSONObject();

    try {
        //Add string params
        jsonParam.put("NAME", "XXXXXXXXXXXXXX");
        jsonParam.put("USERNAME", "XXXXXXXXXXXXXX");
        jsonParam.put("PASSWORD", "XXXXXXXXXXXX");
        jsonParam1.put("NAME", "XXXXXXXXXXXXXX");
        jsonParam1.put("USERNAME", "XXXXXXXXXXXXXX");
        jsonParam1.put("PASSWORD", "XXXXXXXXXXXX");
    } catch (JSONException e) {
        e.printStackTrace();
    }

    array.put(jsonParam);
    array.put(jsonParam1);
    JsonArrayRequest request_json = new JsonArrayRequest(Request.Method.POST, URL, array,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    //Get Final response
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError volleyError) {
            VolleyLog.e("Error: ", volleyError.getMessage());

        }
    }) {
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String, String> headers = new HashMap<String, String>();
            // Add headers
            return headers;
        }
        //Important part to convert response to JSON Array Again
        @Override
        protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
            String responseString;
            JSONArray array = new JSONArray();
            if (response != null) {

                try {
                    responseString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
                    JSONObject obj = new JSONObject(responseString);
                    (array).put(obj);
                } catch (Exception ex) {
                }
            }
            //return array;
            return Response.success(array, HttpHeaderParser.parseCacheHeaders(response));
        }
    };
    queue.add(request_json);
Reganregard answered 15/6, 2018 at 10:25 Comment(2)
You saved my day with this great tip to override parseNetworkResponse!Stronghold
My long search for the most appropriate answer ended here. I appreciate this man. Kudos!Ingaingaberg
B
3
{
"typeName": "MANUFACTURER",
"typeId": 22,
"cityId": 308,
"sortBy": "productname",
"sortOrder": "desc",
"filter":[
            {
                "filterId":101,
                "typeName":"CAT_ID",
             }
             {
                 "filterId":102,
                "typeName":"CAT_ID"
            }
         ]
}


JSONObject object=new JSONObject();
object.put("typeName","");
object.put("typeId","");
object.put("cityId","");
object.put("sortBy","");
object.put("sortOrder","");
JSONArray array=new JSONArray();
JSONObject obj=new JSONObject();
obj.put("filterId","");
obj.put("typeName","");
array.put(obj);
object.put("filter",obj.toString());

pass JSONObject to make request. use this https://www.androidhive.info/2014/09/android-json-parsing-using-volley/

Bucko answered 26/9, 2017 at 9:38 Comment(5)
but there are two filterId i need to add..how will i add it?Chippy
You can create multiple JSONObject and add them to JSONArray.Bucko
its not possible i guess.Chippy
oh yes i created as you said..but now strange issue i am getting..if i add cityId i am not getting response.. but if i remove cityId i am getting response..webservice works fine in postman and other tools..so there is not any issue in webservice..can you help?Chippy
can you help me ?Chippy
T
2

Hope this helps you.

    //Create Main jSon object
    JSONObject jsonParams = new JSONObject();

    try {
        //Add string params
        jsonParams.put("typeName", "MANUFACTURER");
        jsonParams.put("typeId", "22");
        jsonParams.put("cityId", "308");
        jsonParams.put("sortBy", "productname");
        jsonParams.put("sortOrder", "desc");
    } catch (JSONException e) {
        e.printStackTrace();
    }
    //Create json array for filter
    JSONArray array=new JSONArray();

    //Create json objects for two filter Ids
    JSONObject jsonParam1 =new JSONObject();
    JSONObject jsonParam2 =new JSONObject();

    try {

        jsonParam1.put("filterId","101");
        jsonParam1.put("typeName","CAT_ID");

        jsonParam2.put("filterId","102");
        jsonParam2.put("typeName","CAT_ID");
    } catch (JSONException e) {
        e.printStackTrace();
    }

    //Add the filter Id object to array
    array.put(jsonParam1);
    array.put(jsonParam2);

    //Add array to main json object
    try {
        jsonParams.put("filter",array);
    } catch (JSONException e) {
        e.printStackTrace();
    }

For more information on how to create json object check this link

Android JSONObject : add Array to the put method

EDIT:

In case of more data it is better to use Gson convertor

http://www.vogella.com/tutorials/JavaLibrary-Gson/article.html

Also for creating pojo classes use this

http://www.jsonschema2pojo.org/

Tiffanietiffanle answered 28/9, 2017 at 11:20 Comment(2)
nope..there could be n numbers of filterID and typename.. it could be 1 or 5 or 2 ..cant assume it..its dynamicChippy
edited the answer..check now..that is the easiest wayTiffanietiffanle
A
2

Hi Volley does not support JsonArray request better use some other libraries...

Ava answered 5/10, 2017 at 9:12 Comment(1)
Volley being open-source library allows you to customize it source code to introduce new constructors and overrides to methods. So replacing Volley just for such enhanced support is not Wise.Fredela
F
0

Following three steps should make it work for old Volley libraries lacking this suport.

  1. Prepare payload and post:

                        JSONArray payloadItems = new JSONArray();
    
                  JSONObject payloadItem1=new JSONObject();
                 //set properties on item1
                 payloadItem1.put('prop1',"val11");
    
                  payloadItems.put(payloadItem1);
    
                 JSONObject payloadItem2=new JSONObject();
                 //set properties on item1
                 payloadItem2.put('prop1',"val12");
    
                 payloadItems.put(payloadItem1);
    
    
                 JsonArrayRequest request;
    
                 request = new JsonArrayRequest(Request.Method.POST,url,payloadItems, new Response.Listener<JSONArray>() {
                    @SuppressWarnings("unchecked")
                    @Override
                    public void onResponse(JSONArray response) {
                        //your logic to handle response
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        //your logic to handle error
                    }
                }) {
    
                    public Map<String, String> getHeaders() throws AuthFailureError {
                        Map<String,String> params = new HashMap<String, String>();
                        /* This is very important to pass along */
                        params.put("Content-Type","application/json");
                        //other headers if any
                        return params;
                    }
    
                     };
    
    
    
    
                    request.setRetryPolicy(new DefaultRetryPolicy(10000, 2, 2));
                    VolleyHelper.init(this);
                    VolleyHelper.getRequestQueue().add(request);
    
  2. [If Needed] Add this constructor in Class- JsonArrayRequest in Volley package if not already there

      public JsonArrayRequest(int method, String url, JSONArray jsonArray, Listener<JSONArray> listener, ErrorListener errorListener) {
        super(method, url, (jsonArray == null) ? null : jsonArray.toString(),
                listener, errorListener);
    

    }

  3. [If Needed] Override this method if not yet implemented to support JSONArray response from server.

     @Override
     protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
         String responseString;
         JSONArray array = new JSONArray();
         if (response != null) {
    
             try {
                 responseString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
                 JSONObject obj = new JSONObject(responseString);
                 (array).put(obj);
             } catch (Exception ex) {
             }
         }
         //return array;
         return Response.success(array, HttpHeaderParser.parseCacheHeaders(response));
     }
    
Fredela answered 13/1, 2020 at 9:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.