【问题标题】:how to build Below kind of JSON Format to post it as a request in android?如何构建以下 JSON 格式以在 android 中将其作为请求发布?
【发布时间】:2012-06-04 17:17:43
【问题描述】:

需要如下所示的JSON格式发布数据并且数组的size不是 常数。取决于用户。

  {
  "info": [
    {
      "Name": "foo1",
      "Number": 123
    },
    {
      "Name": "foo2",
      "Number": 124
    },
    {
      "Name": "foo2",
      "Number": 125
    }
  ]
}

我尝试通过以下方式创建

JSONObject parent = new JSONObject();
JSONArray jArray = new JSONArray();
JSONObject childObj = new JSONObject();


childObj.put("Name", etName.getText()).toString();
childObj.put("Number", etNumber.getText()).toString();

jArray.put(childObj);

parent.put("info",jArray);

但我无法得到它,我也尝试过这种方式,如example 6.1,但没有像 add for JSONArray 这样的方法。那么如何发布我的数据。请帮我。 谢谢。

【问题讨论】:

    标签: android json post


    【解决方案1】:

    我不确定您的问题到底是什么,但我通常会这样做来创建您正在寻找的 JSON 字符串(下面的示例使用来自 http://www.json.org/java/index.html 的 org.json 参考实现):

    JSONObject parent = new JSONObject();
    JSONArray infoArray = new JSONArray();
    
    
    for(int i = 0; i < SOMEARRAY.length; i++)
    {
        JSONObject childObj = new JSONObject();
        childObj.put("Name", etName.getText());
        childObj.put("Number", etNumber.getText());
        infoArray.put(childObj);
    }
    
    parent.put("info", infoArray);
    
    String encodedJsonString = parent.toString();
    

    【讨论】:

    • 什么不起作用?你必须提供比这更多的细节。你在使用参考实现吗?您是否更改了 for 循环以满足您的需要(或完全删除 for 循环)。仅通过查看您的问题很难知道您要做什么。我的代码中有什么不工作的地方?
    • childObj 没有被添加到数组中。
    • 它应该可以工作,你确定你的代码是正确的吗?尝试使用代码的当前状态更新您的帖子。如果将etName.getText() 更改为硬编码字符串会怎样?你有任何例外吗?您是否进行了修改,以便我添加的 for 循环适用于您的原因?
    • 是的,但正如我之前在 stackoverflow.com/questions/10809975/… 的帖子中一样,我需要添加一些字段,然后我需要从那里获取它,它缺少将其添加到父级
    【解决方案2】:

    我不明白你为什么在将东西放入childObj 后打电话给toString()。 无论如何,这段代码应该可以工作:

    JSONObject parent = new JSONObject();
    JSONArray jArray = new JSONArray();
    JSONObject childObj = new JSONObject();
    
    try
    {
        //create first child
        childObj
            .put("Name", "foo1")
            .put("Number", 123);
    
        //insert it into the array
        jArray.put(childObj);
        //... repeat for all remaining elements
    
        //attach the array to the parent
        parent.put("info",jArray);
    }
    catch (JSONException e)
    {
        e.printStackTrace();
    }
    

    然后,要将您的 JSON 作为字符串进行发布,只需调用 parent.toString();

    【讨论】:

    • 对于我的代码和给你的代码是唯一的差异。是 try catch 块。无论如何我也试过了,但没有改变
    • 他还从每个childObj.put(...) 中删除了.toString()。最后你应该在你的父对象上调用.toString()。
    猜你喜欢
    • 2020-07-20
    • 1970-01-01
    • 2020-12-31
    • 1970-01-01
    • 1970-01-01
    • 2011-09-07
    • 2012-04-02
    • 1970-01-01
    相关资源
    最近更新 更多