1

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.

2 Answers 2

2

Create JSON String using JSONObject and JSONArrayfor sending JSON to server instead of creating it using BasicNameValuePair :

JSONObject json=new JSONObject();
json.put("name", name);

JSONArray jsonArray=new JSONArray();
for (Iterator<MyCoolObject> it = checkedSet.iterator(); it.hasNext(); ) {
    MyCoolObject f = it.next();
    jsonArray.put(f.getUserId());
}

// add jsonArray JSONArray to json JSONObject
json.put("id", jsonArray);

Now use json.toString() for sending required JSON String on Server.

Sign up to request clarification or add additional context in comments.

Comments

1

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]));
}

2 Comments

i accept this answer, i cant up answer because i have not 15 reputation. When will have 15 reputation i up this uswer)
@j2417706 no problem.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.