Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Update JSONArray value on java

Tags:

java

arrays

can anyone help me, i'am new on java programing

let say i have JSONArray with this data below :

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

How to update STATUSUPDATE to 1 in IDSERV 2

How to update STATUSUPDATE to 2 in IDSERV 3

and was trying to loop the 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 anyone help me

like image 513
user3502930 Avatar asked Aug 12 '16 08:08

user3502930


People also ask

How do I pass JSONArray?

Solution: In order to pass the array value to the post action, you need to serialize the array value and pass the serialized data to the mapper action. In the post action, you can de-serialize the serialized data and use the data based on your requirement.

How can we create correct JSONArray in Java using JSON object?

jsonObject. put("key", "value"); Create a JSON array by instantiating the JSONArray class and add, elements to the created array using the add() method of the JSONArray class.

What is JSONArray in Java?

A JSONArray is an ordered sequence of values. Its external text form is a string wrapped in square brackets with commas separating the values. The internal form is an object having get and opt methods for accessing the values by index, and put methods for adding or replacing values.


1 Answers

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);
    }
}
like image 144
Raman Sahasi Avatar answered Oct 14 '22 06:10

Raman Sahasi