How to clear data from a JSON Array

30,356

Solution 1

Just create a new JSONArray.

JSONArray otherJsonArray = new JSONArray();

Or iterate through the array and remove(int index) the indexes.

http://www.json.org/javadoc/org/json/JSONArray.html#remove(int)

Solution 2

Just put jsonArray = new JSONArray()

Solution 3

Creating a new one will work, unless you have passed it as a parameter to a method in which case you need to modify the referenced object as a new reference will not be seen by the calling method.

So if that is the case, do it backwards, that way you won't get your iterator exceeding bounds:

    int startingLength = someJsonArray.length();

    for (int i = startingLength - 1; i >= 0; i--) {

        someJsonArray.remove(i);

    }

Solution 4

And you use that otherJsonArray is already existing then you use

JSONArray otherJsonArray = new JSONArray("[]");
Share:
30,356
Joseph
Author by

Joseph

Updated on August 03, 2021

Comments

  • Joseph
    Joseph almost 3 years

    I am working on a project where I have to clear all the data from a JSON array. There seems to be no method like jsonArray.clear(). Also tried jsonArray = new JSONArray(). That too didn't worked. Suggestions please

  • Joseph
    Joseph about 11 years
    But there is no method remove(int) for JSONArray. My IDE is not showing that. I am using Android development tool(Eclipse)
  • Anew
    Anew about 11 years
    No method remove on JSONArray? It's not static, so that's not surprising. It's an instance method, it would be jsonArray.remove(); unless you're not using the same org.json.JSONArray object?
  • Joseph
    Joseph about 11 years
    Am using org.json.JSONArray object. I changed that object to static and still it don't have the method remove()
  • Anew
    Anew about 11 years
    You've misunderstood me, the method should exist on the instance (jsonArray), not on the JSONArray class as a static method.
  • Gastón Saillén
    Gastón Saillén over 5 years
    if you iterate incrementally to remove(index) , first time will be 0 and will delete lets say from A,B,C "A" after the second loop with 1 it will delete "C" and for the 3rd loop it will not delete nothing since there is no more things after C , so it will return B and will not delete all the array, you need to iterate decrementally to do it