I want to remove "status": "new" from JSON that I have stored in jsonObject using
JSONParser parser = new JSONParser();
Object obj = parser.parse(responseStr);
jsonObject = (JSONObject) obj;
JSON structure --
{"actionName": "test"
"Data": [{
"isActive": true,
"Id": "1358",
"status": "new"
}],
}
new JSON should look like this -
{"actionName": "test"
"Data": [{
"isActive": true,
"Id": "1358"
}],
}
I have tried jsonObj.remove("status") , but no luck.
jsonObj.getJSONArray("Data").get(0).remove("status);
#Updated Code-breakdown:
JSONObject obj= (JSONObject) jsonObj.getJSONArray("Data").get(0);
obj.remove("status");
JSONArray newArr=new JSONArray();
newArr.put(obj);
jsonObj.put("Data", newArr);
It should do your work, haven't tested though. First, your Data
is JSONArray, retrieving that by jsonObj.getJSONArray("Data")
, then access the array with get(0)
[assuming, your array will contain only one entry like your example] and finally, removing that key by remove
method.
You need to iterate over Data
property which is a JSON Array
and remove for every item status
key.
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import java.io.File;
import java.io.FileReader;
public class JsonSimpleApp {
public static void main(String[] args) throws Exception {
File jsonFile = new File("./resource/test.json").getAbsoluteFile();
JSONParser parser = new JSONParser();
JSONObject root = (JSONObject) parser.parse(new FileReader(jsonFile));
JSONArray dataArray = (JSONArray) root.get("Data");
dataArray.forEach(item -> {
JSONObject object = (JSONObject) item;
object.remove("status");
});
System.out.println(root);
}
}
Above code prints:
{"Data":[{"Id":"1358","isActive":true}],"actionName":"test"}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.