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
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.
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.
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.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With