来自Arraylist的JSON创建

时间:2017-04-10 05:07:07

标签: java json

我必须创建类似下面的JSON响应。

    [{"Name":"Shampoo","Qty":"3","Amt":"300"},
    {"Name":"Soap","Qty":"1","Amt":"50"}]

代码:

    ArrayList<String> al= new ArrayList<String>();
    al.addAll(name);
    al.addAll(qty);
    al.addAll(price);

    Gson gson = new Gson();
    String json = gson.toJson( al );

    System.out.println(json);
    JSONObject pa = new JSONObject();
    childData = new JSONObject();

    try {
        childData.put("Name", name);
        childData.put("Qty", qty);
        childData.put("Amt", price);
        pa.put("Detais",childData);

    } catch (JSONException e) {
        e.printStackTrace();
    }

但是上面的代码会像这样创建响应

      {"Name":"[Shampoo, Soap]","Qty":"[3, 1]","Amt":"[300, 50]"}

1 个答案:

答案 0 :(得分:0)

al.addAll()来电中,我推断nameqtyprice是列表。所以你要将列表交给childData.put()个电话。这将生成您找到的输出,以及每个JSON键(子元素)的值数组,其中包含传递给childData.put()调用的列表中的所有元素。

如果你想要你的第一个JSON,你应该遍历列表中的所有元素,并在类似于你的(名称,数量,价格)对的父元素上逐个添加(放置)它们。 E.g。

JSONArray jA  = new JSONArray()
for(int j=0; j<condition;j++){
    JSONObject pa = new JSONObject();
    for(int i=0; i<name.length;i++) {
        childData = new JSONObject();
        childData.put("Name", name[i]);
        childData.put("Qty", qty[i]);
        childData.put("Amt", price[i]);
        pa.put("Detais",childData);
    }
    jA.put(pa);
}