Timothy Rajan Timothy Rajan - 2 months ago 21
Java Question

Remove JSON object from JSONArray - Jettison

Is there a direct way to remove an JSONObject stored in the JSONArray by using index. I tried all the possibilities. Still not able to remove the JSON object from the JSON Array. Any hint will be helpful
Thanks

Answer

In java-json , there is no direct method to remove jsonObject, but using json-simple , it is simple to do so:

        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        JSONObject jsonObject1 = new JSONObject();
        JSONObject jsonObject2 = new JSONObject();
        jsonObject.put("key1", "value1");
        jsonObject1.put("key2", "value2");
        jsonObject2.put("key3", "value3");
        jsonArray.add(jsonObject);
        jsonArray.add(jsonObject1);
        jsonArray.add(jsonObject2);

        //........ Whole Json Array
        System.out.println(jsonArray);


        //To remove 2nd jsonObject (index starts from 0)

        jsonArray.remove(1);


        // Now the array will not have 2nd Object
        System.out.println(jsonArray);