【问题标题】:Android JSONObject : add Array to the put methodAndroid JSONObject:将数组添加到 put 方法
【发布时间】:2013-09-01 21:45:08
【问题描述】:
// 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"
  ]
}

【问题讨论】:

    标签: java android jsonobject


    【解决方案1】:

    看到示例后,我了解到您正在尝试做与Java JsonObject array value to key 中所要求的类似的事情

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

    为了简化:

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

    【讨论】:

    • 我认为这不是我的问题的解决方案。我添加了一个我需要的示例。看一看。谢谢
    • 非常感谢!现在我明白了!
    【解决方案2】:
    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);
    

    【讨论】:

    • 最好能解释一下为什么你的代码可以工作。
    • 如果你想在对象中创建一个数组,它会起作用,是的,它对我有用!
    • 什么是itemList??
    【解决方案3】:

    您必须将数组显式添加为 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));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-21
      • 2021-06-21
      • 1970-01-01
      • 1970-01-01
      • 2019-03-29
      相关资源
      最近更新 更多