0

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 Answers1

0

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++;
}