Send a Json array POST request with android using volley

笑着哭i 提交于 2021-02-11 12:13:42

问题


i am developing application in which i send data to server using volley now i want to send data to server in json array but not know how to send in array??

    Map<String, String> postParam = new HashMap<String, String>();

    postParam.put("Token", "U2FsdGVkX13CFEM=");
    postParam.put("AppDB", "day");
    postParam.put("ContentTypeName", "Users");



    JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
            AppConfig.URL_REGISTER_WITHOUT_IMG, new JSONObject(postParam),
            new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    Log.d(TAG, response.toString());
                    //     msgResponse.setText(response.toString());
                    //  hideProgressDialog();
                }
            }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d(TAG, "Error: " + error.getMessage());
            // hideProgressDialog();
        }
    }) {

        /**
         * Passing some request headers
         * */
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type", "application/json; charset=utf-8");
            return headers;
        }
    };

    jsonObjReq.setTag(TAG);
    // Adding request to request queue
    Volley.newRequestQueue(this).add(jsonObjReq);

}

now i want to send data in array expected json { "AppDb":"day", "ContentTypeName":"Users", "Token":"U2FsdGVkX13CFEM=", "FilterData":[ {"FilterName":"EmailId","FilterValue":" Pass the user enter email here to check"} ]

}


回答1:


Try this:

JSONArray jsonArray=new JSONArray();
JSONObject jsonObj=new JSONObject();
try {
    jsonObj.put("filterName","EmailId");
    jsonObj.put("FilterValue",// user email);
} catch (JSONException e) {
    e.printStackTrace();
}
jsonArray.put(jsonObj);

Add it to your params like this:

postParam.put("FilterData",jsonArray);



回答2:


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() { @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;
    }
    
     };
    
  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));
     }
    


来源:https://stackoverflow.com/questions/52131382/send-a-json-array-post-request-with-android-using-volley

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!