0

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.

2 Answers 2

1
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.

Sign up to request clarification or add additional context in comments.

5 Comments

hi thank you for the prompt reply, but i am getting the method getJSONArray(String) is undefined for the type JSONObject error.
what library are you using? org.json or Jackson?
org.json.simple.JSONObject
The method getJSONArray(String) is undefined for the type JSONObject--still facing same issue
I was using lib from this, please have a look here mvnrepository.com/artifact/org.json/json/20190722
0

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"}

2 Comments

it is working! thanks! One follow up question what if we have to remove more than one key value pair ? l
@user1992728, JSONObject is just a Map object with extra methods. You can remove as many keys as you want. In forEach method you can remove all keys specified in an array for example. Iterate over this array and remove every key from JSONObject.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.