Android JSONObject:将Array添加到put方法


问题内容

// 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", arrayOfElements);

其中arrayOf Elements必须是字符串数组。我能怎么做?

/ ** 编辑

我需要的例子

{
  "action": "myAction",
  "type": "elementi",
  "elementi": [
    "3287498357",
    "23472857"
  ]
}

问题答案:

看完示例后,我了解到您正在尝试执行与JavaJsonObject数组中的键值要求类似的操作

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

为了简化:

JSONArray arr = new JSONArray();
arr.put("value1");
arr.put("value2");
//...
jsonObjSend.put("elementi", arr);