4

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

2

3 Answers 3

6

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);
Sign up to request clarification or add additional context in comments.

2 Comments

This method required at least API level 19.
API level refers to the Android SDK (which you do not need to care about if you are not programming for Android, as seems to be the case in this question)
0

Have you tried using delete to do this?

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete

2 Comments

Thanks for that. I need to delete it using JAVA. Could you please help me with JAVA code. I tried all API's. Might be I am missing something.
No. I am looking for a remove method or something similar. Not able to get it. If this doesnt work, I need to convert the JSONArray to a Normal array and remove. Lot of coding involved. Looking to avoid it.
0

just get the index of the JSON object in the json array

and remove the json object by array.splice(index,howmany,item1,.....,itemX) method

for more information just use this link http://www.w3schools.com/jsref/jsref_splice.asp

1 Comment

Thanks for this. I believe your solution holds good for JAVAscript. I am looking for a JAVA solution

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.