简体   繁体   中英

How to send Array as Body to a Web Service in android with Volley library?

I'm trying to send a data as an array to a web service and I using Volley library to do that, but in a part of my code I should send an Array as Body. So I'm using the below code for another part of my project then give a JSON object as a body but now I want to send a body as an array. my array

[
  {
    "name": "a",
    "family": "f"
  },
  {
    "name": "b",
    "family": "f"
  },
  {
    "name": "c",
    "family": "f"
  }
]

String url = "";
            try {
                JSONObject jsonBody = new JSONObject();
                jsonBody.put("name", name); 
                jsonBody.put("family", family); 
                //request a json object response
                JsonObjectRequest jsonRequest = new JsonObjectRequest( Request.Method.POST, url, jsonBody, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {


                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                    error.printStackTrace();
                    }
                }) {    //this is the part, that adds the header to the request
                    @Override
                    public Map<String, String> getHeaders() {
                        Map<String, String> params = new HashMap<String, String>();
                        params.put("Content-Type", "application/json; charset=utf-8");
                        return params;
                    }
                };
                // Add the request to the queue
                Volley.newRequestQueue(Activity_Goods_List.this).add(jsonRequest);
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(), e.getMessage().toString(), Toast.LENGTH_LONG).show();
            }

Add your objects to array-like this

Let us assume you have a list of names and family

    JSONArray request=new JSONArray();
    for(int i=0; i<names.size; i++){
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("name", names.get(i));
        jsonBody.put("family", family.get(i));
        request.put(jsonBody);
    }
    // You'll have array ready here for your request

You can send as a json array. Encode the Array into JSON and sent to your backed. From your backend, you can parse JSON and retrieve back the array. You can't directly send the array, You have to follow data transfer formats like json or xml

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM