j2417706 j2417706 - 23 days ago 6
Android Question

Cant send array to server using nameValuePairs(android)

Sorry for my english. My people gave me a project and I need to change some POST requests. I used

retrofit
before, but this project uses
org.apache
.
I know that it's bad, but I only need to send an array to the server. I tried it many times but it doesn't work. I need to send the server something like this:

{"name": "hellow", "id": [{"1"}, {"2"}]}


Here is what I tried to do:

1.

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("link");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name", name));

int i = 0;
for (Iterator<MyCoolObject> it = checkedSet.iterator(); it.hasNext(); ) {
MyCoolObject f = it.next();
nameValuePairs.add(new BasicNameValuePair("id[" + String.valueOf(i)+ "]", f.getUserId()));
i++;
}


2.

ArrayList<String> array = new ArrayList<String>();
for (Iterator<MyCoolObject> it = checkedSet.iterator(); it.hasNext();) {
MyCoolObject f = it.next();
array.add(f.getUserId());
}
nameValuePairs.add(new BasicNameValuePair("id", array.toString()));


3.

JSONArray jsonArray = new JSONArray();
for (Iterator<MyCoolObject> it = checkedSet.iterator(); it.hasNext(); ) {
MyCoolObject f = it.next();
jsonArray.put(f.getUserId());
}
nameValuePairs.add(new BasicNameValuePair("id", jsonArray.toString()));


None of them worked, I don't know what do.

Answer

Try it out I am not sure its working in your case or not.

 nameValuePairs.add(new BasicNameValuePair("id", type[i]));

Use for loop to wrap your array.

for (int i = 0; i < type.length; i++) {
nameValuePairs.add(new BasicNameValuePair("id[]",type[i]));
}