android - 如何从 Arraylist 值创建 Json?

标签 android json arraylist

我在 arraylist 中有两个项目

  • 位置 0:product_id=500,amout=1
  • 位置 1:product_id=501,amout=1

我想创建这种类型的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);
}

I am getting this Responce:

 {
 "user_id":"230",
 "shipping_id":"1",
 "payment_id":"14",
  "products":[
     {"579":
     {
        "product_id":"579",
        "amount":"1"
        }
     },
     {"593":
        {
        "product_id":"593",
        "amount":"1"
        }
        }]

But I want this json Responce please help for getting resultant responce. { "user_id": "3", "shipping_id": "1", "payment_id": "2", "products": { "500": { "product_id": "500", "amount": "1" }, "501": { "product_id": "501", "amount":"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();
    }

关于android - 如何从 Arraylist 值创建 Json?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44736343/

相关文章:

android - 如何使用android默认图库打开特定文件夹图像

javascript - D3.js JSON解析错误

python - Django Rest Framework 不序列化 SerializerMethodField

java - 如何解析示例中给出的数组列表?

java - 如何在JList中显示模型的值?

android - 从 asset 文件夹加载的图像与 res/drawable 的大小不同

java - 如何知道 Android 应用程序中正在使用哪些库

json - jsonrequest 和 httprequest 有什么区别?

java - 如何追踪银行账户余额?

android - 为什么 VTS 因不准确的 adb 错误而失败?