Array as Volley POST request params

穿精又带淫゛_ 提交于 2019-12-11 09:29:21

问题


I am trying to make a volley POST request with a array as my parameter, for example I want to POST

{"types":[1,2,3]} 

what I have now is a string

{"types":"[1,2,3]"}

This is how I made my volley request:

JSONArray jsonArray = new JSONArray();
JSONObject jsonObject = new JSONObject();

    try{
        jsonObject.put("types", list);
        jsonArray.put(jsonObject);
        System.out.println(jsonObject);
    }catch(Exception e){

    }

    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, jsonObject,
            new Response.Listener<JSONObject>(){
                @Override
                public void onResponse(JSONObject response) {
                    Log.e("Response", response.toString());
                }
            },
            new Response.ErrorListener(){
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.e("Error.Response", error.toString());
                    String json = null;
                    NetworkResponse response = error.networkResponse;
                    if(response != null && response.data != null){
                        switch(response.statusCode){
                            case 400:

                                json = new String(response.data);
                                System.out.println(json);
                                break;
                        }
                    }
                }
            })
    {
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<>();
            headers.put("Authorization", Token);
            return headers;
        }
    };

    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(jsonObjectRequest);

List is an array list declared as:

List<Integer> list = new ArrayList<Integer>();

I am assuming that jsonObject.put("types", list) will turn my array into a list, how should I solve this problem?


回答1:


Instead of List, try JSONArray.

JSONArray types=new JSONArray();
types.put(1);
types.put(2);
types.put(3);
jsonObject.put("types", types);
jsonArray.put(jsonObject);

This should fix your issue



来源:https://stackoverflow.com/questions/41870263/array-as-volley-post-request-params

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