【问题标题】:How to loop over an array of data that saved to a JSONObject and put it in a JSONArray?如何遍历保存到 JSONObject 的数据数组并将其放入 JSONArray?
【发布时间】:2020-09-16 21:05:14
【问题描述】:

我的 HTML 中有字段,例如我在控制器上循环的 2 行字段。

我希望它得到这样的结果:

{
"specifications":
[
    {
      "name" : "height",
      "value" : "cm"
    },
    {
      "name" : "weight",
      "value" : "kg"
    }
  ]
}

但每次我使用下面的代码循环时,我只会将迭代的最后一行保存到我的 JSONArray 中

JSONObject itemTypeObj = new JSONObject();
JSONArray itemTypeArray = new JSONArray();
JSONObject itemTypeSpecs = new JSONObject();
ArrayList<String> values = new ArrayList();

        for(int x = 0; x < specName.length; x++){

            itemTypeSpecs.put("specName", specName[x]);

            if (specValue[x].contains(",")) {

                for (String v : specValue[x].split(",")) {
                    values.add(v.trim());
                }

                itemTypeSpecs.put("specValue", values);
            } else {
                itemTypeSpecs.put("specValue", specValue[x]);
            }

            values.clear();

            itemTypeArray.put(itemTypeSpecs);

        }

itemTypeObj.put("specifications", itemTypeArray);

结果变成了这样,而不是我期望的结果

{"specifications":
  [
   {
    "name":"Weight",
    "value":"kg"
   },
   {
    "name":"Weight",
    "value":"kg"
   }
  ]
}

我找不到它只获得最后一行的原因。任何帮助表示赞赏。谢谢。

【问题讨论】:

  • 你应该添加你的输入

标签: java arrays json spring-boot object


【解决方案1】:

你应该在第一个“for循环”中创建数组列表和JSONObject。因为你总是改变相同的对象你可以试试这个吗?

        JSONObject itemTypeObj = new JSONObject();
        JSONArray itemTypeArray = new JSONArray();

        for (int x = 0; x < specName.length; x++) {
            List<String> values = new ArrayList();
            JSONObject itemTypeSpecs = new JSONObject();
            itemTypeSpecs.put("specName", specName[x]);

            if (specValue[x].contains(",")) {
                for (String v : specValue[x].split(","))
                    values.add(v.trim());
                itemTypeSpecs.put("specValue", values);
            } else {
                itemTypeSpecs.put("specValue", specValue[x]);
            }
            itemTypeArray.put(itemTypeSpecs);
        }
        itemTypeObj.put("specifications", itemTypeArray);

【讨论】:

  • 我试过这个,它似乎得到了我需要的结果,所以我接受这个作为我问题的答案。太感谢了! :)
猜你喜欢
  • 2022-11-14
  • 1970-01-01
  • 1970-01-01
  • 2011-05-27
  • 2021-02-11
  • 2020-01-23
  • 2018-05-20
  • 2021-11-04
  • 2016-01-08
相关资源
最近更新 更多