Java Android JSONObject : 将 Array 添加到 put 方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18563267/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android JSONObject : add Array to the put method
提问by Usi Usi
// 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?
其中 arrayOf Elements 必须是字符串数组。我能怎么做?
/**EDIT
/ **编辑
EXAMPLE OF WHAT I NEED
我需要什么的例子
{
"action": "myAction",
"type": "elementi",
"elementi": [
"3287498357",
"23472857"
]
}
采纳答案by Shobhit Puri
After seeing the example I understood that you are trying to do something similar as asked in Java JsonObject array value to key
看到示例后,我了解到您正在尝试执行类似于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);
回答by vineet
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);