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
-
I need to accomplish task using JAVA. forget to add it in the questionTimothy Rajan– Timothy Rajan2013-11-07 13:53:07 +00:00Commented Nov 7, 2013 at 13:53
-
possible duplicate of How do I remove a specific element from a JSONArray?C--– C--2014-01-28 03:31:26 +00:00Commented Jan 28, 2014 at 3:31
Add a comment
|
3 Answers
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);
2 Comments
Mansour Fahad
This method required at least API level 19.
personne3000
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)
Have you tried using delete to do this?
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete
2 Comments
Timothy Rajan
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.
Timothy Rajan
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.
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
Timothy Rajan
Thanks for this. I believe your solution holds good for JAVAscript. I am looking for a JAVA solution