我必须创建类似下面的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]"}
答案 0 :(得分:0)
在al.addAll()
来电中,我推断name
,qty
和price
是列表。所以你要将列表交给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);
}