我在arraylist中有两个项目
我想创建这种类型的json
{
"user_id": "3",
"shipping_id": "1",
"payment_id": "2",
"products": {
"500": {
"product_id": "500",
"amount": "1"
},
"501": {
"product_id": "501",
"amount":"1"
}
}
}
这是我的代码
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("user_id", usr);
jsonObject.accumulate("shipping_id", shipping_id);
jsonObject.accumulate("payment_id", payment_id);
for( i=0;i<alProductss.size();i++) {
String a = alProductss.get(i).getAnount();
String b = alProductss.get(i).getProduct_id();
JSONObject productObject = new JSONObject();
jsonObject.accumulate("products", productObject);
JSONObject numberObject = new JSONObject();
numberObject.accumulate("product_id", b);
numberObject.accumulate("amount", a);
productObject.accumulate(b, numberObject);
}
我收到此回应:
{
"user_id":"230",
"shipping_id":"1",
"payment_id":"14",
"products":[
{"579":
{
"product_id":"579",
"amount":"1"
}
},
{"593":
{
"product_id":"593",
"amount":"1"
}
}]
}
但我希望这个json回复请帮助获得最终的回应。
{ "user_id": "3", "shipping_id": "1", "payment_id": "2", "products": { "500": { "product_id": "500", "amount": "1" }, "501": { "product_id": "501", "amount":"1" } } }
答案 0 :(得分:1)
尝试这个..
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("user_id", usr);
jsonObject.accumulate("shipping_id", shipping_id);
jsonObject.accumulate("payment_id", payment_id);
JSONArray jsonArray = new JSONArray();
for( i=0;i<alProductss.size();i++) {
String a = alProductss.get(i).getAnount();
String b = alProductss.get(i).getProduct_id();
JSONObject productObject = new JSONObject();
JSONObject numberObject = new JSONObject();
numberObject.accumulate("product_id", b);
numberObject.accumulate("amount", a);
jsonArray.put(numberObject);
}
jsonObject.put("products",jsonArray);
答案 1 :(得分:1)
您可以使用以下代码生成JSON,
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("user_id", usr);
jsonObject.put("shipping_id", shipping_id);
jsonObject.put("payment_id", payment_id);
JSONObject productValueObject = new JSONObject();
for (int i = 0; i < alProductss.size(); i++) {
String a = alProductss.get(i).getAmount();
String b = alProductss.get(i).getProduct_id();
JSONObject projectObj = new JSONObject();
projectObj.put("product_id", b);
projectObj.put("amount", a);
productValueObject.put(b, projectObj);
}
jsonObject.put("products", productValueObject);
} catch (JSONException e) {
e.printStackTrace();
}