Android JSONObject:向put方法添加数组

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

目前一切都很好,但如果我想添加

jsonObjSend.put("elementi", arrayOfElements);

arrayOf Elements 必须是一个字符串数组。我该怎么做?

/** 编辑

我需要的示例

{
  "action": "myAction",
  "type": "elementi",
  "elementi": [
    "3287498357",
    "23472857"
  ]
}
3个回答

51

看了这个例子之后,我明白你正在尝试做与Java JsonObject数组值转键类似的事情。

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

简而言之:

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

1
我认为那不是我的问题的解决方案。我添加了一个我需要的示例,请看一下。谢谢。 - Usi Usi

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

1
最好能解释一下你的代码为什么会起作用。 - Anh Pham
如果你想在对象内创建一个数组,它会起作用,对我来说也是如此! - vineet
2
itemList是什么? - qkzoo1978

0

你需要将数组明确地添加为JSONArray对象:

// 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));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接