java - 通过@Requestbody Spring MVC传递多个数据,JSONobject没有得到更新
问题描述
我在循环中更新 JSON 对象时遇到问题,我在 json 对象中得到了覆盖的数据。
来自 UI 的 JSON 请求
{
"attribute":[
{
"name":"Program",
"status":"Active"
},
{
"name":"Software",
"status":"Active"
}
]
}
Java 代码
JSONObject response = new JSONObject();
JSONObject obj = new JSONObject();
JSONArray res = new JSONArray();
int i=1;
for (AttributeList attr_list : addmodel.getAttribute()) {
response.put("name", attr_list.getAttribute_nm());
response.put("status", attr_list.getCategory());
res.add(response);
System.out.println("inloop--res "+res);
obj.put(i, res);//issue is here
System.out.println("inloop--obj "+obj);
i++;
}
输出
["1": {"name":"Software","status":"Active"}, "2":{"name":"Software","status":"Active"}]
两个位置的数据都被覆盖。
抱歉,我无法输入整个代码。
解决方案
您需要创建新的 JSONObject response = new JSONObject(); 再次在循环中获取下一个值。 原因:由于您没有为列表中的每个值创建新对象,因此先前的引用将被新值替换。
JSONObject response = null;
JSONObject obj = new JSONObject();
JSONArray res = new JSONArray();
int i=1;
for (AttributeList attr_list : addmodel.getAttribute()) {
response = new JSONObject();
response.put("name", attr_list.getAttribute_nm());
response.put("status", attr_list.getCategory());
res.add(response);
System.out.println("inloop--res "+res);
obj.put(i, res);//issue is here
System.out.println("inloop--obj "+obj);
i++;
}
推荐阅读
- swift - 精灵套件;如何将 AVPlayer() 嵌入 SKScene?
- cflow - cflow 只显示某些函数的父级
- python - timeit.timeit 以科学计数法返回时间?
- python-3.x - AsyncElasticsearch 客户端不接受与 AWS Elasticsearch 的连接 - AttributeError: 'AWS4Auth' object has no attribute 'encode'
- javafx - JavaFX 属性:fireValueChangedEvent
- reactjs - React Redux 句柄事件成功完成
- logging - Windows 10 IoT UWF 不保留事件查看器日志
- javascript - 根据vue js中的用户角色权限将用户重定向到特定仪表板
- .net-core - MassTransit SignalR 绑定
- google-cloud-platform - 如何通过 MQL 获取 GCP 计算虚拟机实例的正常运行时间总数和百分比?