Android_Code_Chef
Android_Code_Chef

Reputation: 915

Android sending JsonObject with json array

I need to post one request to server. Format i need to send is : { “userId”: , “array”: ("A,"b","c",...) }

I can send the jsonobject but i don't know how to send JsonObejct and Jsonarray together in one request.

Upvotes: 0

Views: 8434

Answers (3)

Knickedi
Knickedi

Reputation: 8787

Is it that easy how I think?

JSONObject json = new JSONObject();
JSONArray array = new JSONArray();

for (String string : new String [] {"A", "b", "c", ...}) {
    array.put(string);
}

json.put("userId", theId);
json.put("array", array);
sendYourRequest(json);

// This is wrong! Code corrected. Thank you for the Feedback!!!
// json.put("array", new String [] {"A", "b", "c", ...});

Upvotes: 3

Jim Baca
Jim Baca

Reputation: 6132

You need to create a JSONObject and a JSONArrayObject. Add all the items you want in your json array. Then add the json array into the JsonObject. See below:

JSONArray array = new JSONArray();
array.put("1st array item");
array.put("2nd array item");

JSONObject holder = new JSONObject();       
holder.put("array", array);
holder.put("other_params", ...);

Then you can also verify that the json looks valid by doing the following:

String jsonString = holder.toString(); //verify that the json is in the correct format

Upvotes: 1

Lalit Poptani
Lalit Poptani

Reputation: 67286

Here is a nice JSON Encoding Tutorial refer this.

Upvotes: 0

Related Questions