首页 > 解决方案 > 通过@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"}]

两个位置的数据都被覆盖。

抱歉,我无法输入整个代码。

标签: javaspringspring-mvcmodel-view-controller

解决方案


您需要创建新的 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++;
}

推荐阅读