java - 如何遍历保存到 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"
}
]
}
我找不到它只得到最后一行的原因。任何帮助表示赞赏。谢谢你。
解决方案
你应该在第一个“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);
推荐阅读
- javascript - 尝试在 Django 应用程序的 js 文件中导入 vue.js 时出现“未捕获的语法错误:无法在模块外使用 import 语句”
- sql - 加入两个表以获取匹配的记录和不匹配的记录
- html - 反应中文本输入的动态颜色
- javafx - 如何在 JavaFX (JFoenix) 中显示类似 Android 的吐司消息?
- kubernetes - 我可以在不通过 Terraform 声明任何服务的情况下通过 Terrafrom 设置 Kubernetes Ingress 吗?
- python - Python Pandas,根据另一列中的值进行日期时间舍入
- bash - 为什么从 automator 或 AppleScript 启动 shell 脚本与从终端启动时得到不同的结果?
- ansible - 带有特殊变量的 Ansible 查找插件
- android - 获取没有字符串名称的jsonarray
- sql - 将数据从一个表传输到另一个表