11
// JSON object to hold the information, which is sent to the server
JSONObject jsonObjSend = new JSONObject();
jsonObjSend.put("action", "myAction");
jsonObjSend.put("type", tipo);

For now is everything ok but if I want to add

jsonObjSend.put("elementi", arrayOfElements);

where arrayOf Elements must be an array of strings. How can I do?

/** EDIT

EXAMPLE OF WHAT I NEED

{
  "action": "myAction",
  "type": "elementi",
  "elementi": [
    "3287498357",
    "23472857"
  ]
}
Usi Usi
  • 2,967
  • 5
  • 38
  • 69

3 Answers3

51

After seeing the example I understood that you are trying to do something similar as asked in Java JsonObject array value to key

jsonObjSend.put("elementi", new JSONArray(new Object[] { "value1", "value2", "value3"} ));

To simplify:

JSONArray arr = new JSONArray();
arr.put("value1");
arr.put("value2");
//...
jsonObjSend.put("elementi", arr);
Community
  • 1
  • 1
Shobhit Puri
  • 25,769
  • 11
  • 95
  • 124
  • 1
    I think that isn't the solution for my problem. I add an example of what I need. Take a look. Thanks – Usi Usi Sep 01 '13 at 21:58
0
JSONObject jsonBody = new JSONObject();
jsonBody.put("action", "myAction"); //action is your string
jsonBody.put("type", "elementi");
JSONArray arr = new JSONArray();
JSONObject elementi= new JSONObject();
itemList.put("id", id);
itemList.put("name", name);
arr.put(elementi);
jsonBody.put("elementi", arr);
Anh Pham
  • 2,108
  • 9
  • 18
  • 29
vineet
  • 1
  • 2
0

You have to explicitly add the array as a JSONArray object:

// JSON object to hold the information, which is sent to the server
JSONObject jsonObjSend = new JSONObject();
jsonObjSend.put("action", "myAction");
jsonObjSend.put("type", tipo);
jsonObjSend.put("elementi", JSONArray(arrayOfElements));
simpleuser
  • 1,617
  • 25
  • 36