英文:
Passing multiple data through @Requestbody Spring MVC, JSONobject is not getting updated
问题
在循环中更新 JSON 对象时,我遇到了问题,JSON 对象中的数据被覆盖了。
来自用户界面的 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); // 问题在这里
System.out.println("inloop--obj " + obj);
i++;
}
输出
{
"1": {
"name": "Software",
"status": "Active"
},
"2": {
"name": "Software",
"status": "Active"
}
}
数据在两个位置都被覆盖了。
抱歉,我无法放置完整的代码。
英文:
I am facing issue while updating JSON object in loop, I am getting overwritten data in json object.
JSON Request from UI
{
"attribute":[
{
"name":"Program",
"status":"Active"
},
{
"name":"Software",
"status":"Active"
}
]
}
Java COde
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++;
}
Output
["1": {"name":"Software","status":"Active"}, "2":{"name":"Software","status":"Active"}]
Data is getting overwritten in both positions.
Sorry I'm not able to put whole code.
答案1
得分: 0
在循环中需要再次创建新的 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); // 问题出在这里
System.out.println("inloop--obj " + obj);
i++;
}
英文:
You need to create new JSONObject response = new JSONObject(); again in the loop for next value.
Reason: Since you are not creating a new object for each value in the list, the previous reference is getting replaced by the new value.
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++;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论