How to update JSONArray value in java

can someone help me, i'm new to java programming

let's say I have a JSONArray with this data below:

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

How do I upgrade STATUSUPDATEto 1inIDSERV 2

How do I upgrade STATUSUPDATEto 2inIDSERV 3

and tried to loop data

for (int i=0; i < array.length; i++){
JSONObject itemArr = (JSONObject)array.get(j);
if(itemArr.get("IDSERV").equals(2)){
//should be itemArr.set(with new val) 
//but method *set* can cal; only on JSONArray not an JSONObject
//and looping the next one 
}
}

can someone help me

+4
source share
3 answers

Here is the code:

array - 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 type array, you will see that the values ​​are changed.

+1
source

JSONArray the 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"}]

the 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);
    }
}
+5
source

replaceAll:

String json = ...
json.replaceAll("(?<=\"IDSERV\":\")\\d*(?=\")", new value);

IDSERV.
IDSERV, \\d [] .
 : [1] , 1.

EDIT1:
, .

IDSERV STATUSUPDATE.

(?<=:)\d*(?=,"IDSERV":"1")

1 IDSERV, .

java, :

String json = ...
json.replaceAll("(?<=:)\\d*(?=,\"IDSERV\":\"1\")", new value);
0

Source: https://habr.com/ru/post/1651037/


All Articles