How to Update JSONArray value on java

JSONArray specific code:

Output

Initial array : [{"STATUSUPDATE":0,"IDSERV":"2"},{"STATUSUPDATE":0,"IDSERV":"3"},{"STATUSUPDATE":0,"IDSERV":"1"}]
Output array : [{"STATUSUPDATE":"1","IDSERV":"2"},{"STATUSUPDATE":"2","IDSERV":"3"},{"STATUSUPDATE":0,"IDSERV":"1"}]

Code

public class Test {
    public static void main(String[] args) throws JSONException {
        JSONArray array = new JSONArray("[{\"STATUSUPDATE\":0,\"IDSERV\":\"2\"},{\"STATUSUPDATE\":0,\"IDSERV\":\"3\"},{\"STATUSUPDATE\":0,\"IDSERV\":\"1\"}]");
        System.out.println("Initial array : " + array);

        for (int i=0; i < array.length(); i++){
            JSONObject jsonObject = new JSONObject(array.get(i).toString());
            if(jsonObject.get("IDSERV").equals("2")) {
                jsonObject.put("STATUSUPDATE", "1");
                array.put(i, jsonObject);
            }
            else if(jsonObject.get("IDSERV").equals("3")) {
                jsonObject.put("STATUSUPDATE", "2");
                array.put(i, jsonObject);
            }
        }

        System.out.println("Output array : " + array);
    }
}

Here is the code:

array is your JSONArray

for (int i=0; i < array.length(); i++){
    JSONObject itemArr = (JSONObject)arr.get(i);
    if(itemArr.get("IDSERV").getAsString().equals("2")){
        itemArr.put("STATUSUPDATE", 1);
    }else if(itemArr.get("IDSERV").getAsString().equals("3")){
        itemArr.put("STATUSUPDATE", 2);
    }
}

Now, if you print array then you can see values are changed.

Tags:

Java

Arrays