首页 > 解决方案 > 如何遍历保存到 JSONObject 的数据数组并将其放入 JSONArray?

问题描述

我的 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"
   }
  ]
}

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

标签: javaarraysjsonspring-bootobject

解决方案


你应该在第一个“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);

推荐阅读