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
6 Answers
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)
5 Comments
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?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);
}
Comments
I have a situation where I want to remove all the entries from a JSONArray with key "Constants", which is an element in a JSONObject, creating a new JSONArray an assigning it does NOT clear the JSONArray, I have to iterate through the JSONArray and jsonArray.remove(i) on each of them, but there is a second method that works which involves removing the array element, in this case "Constants" completely from the JSONObject and re-adding it as a new JSONArray.
Hereis code with assignment of new array, which does not work, the JSONArray remained unchanged: (I tried both above suggestions for new JSONArray(); and new JSONArray("[]");
JSONObject jsonObj = new JSONObject(metadataOriginalJSON);
if (jsonObj.isJSONArray("Constants")) {
JSONArray constantsArray = jsonObj.getJSONArray("Constants");
constantsArray = new JSONArray();
metadataConstantsRemoved = jsonObj.toString();
}
Here is code for the iteration through the JSONArray which worked:
JSONObject jsonObj = new JSONObject(metadataOriginalJSON);
if (jsonObj.isJSONArray("Constants")) {
JSONArray constantsArray = jsonObj.getJSONArray("Constants");
int i = 0;
int arrayLenSanityCheckPreventEndlessLoop = constantsArray.length();
while (constantsArray.length() > 0 && i < arrayLenSanityCheckPreventEndlessLoop) {
constantsArray.remove(0);
i++;
}
metadataConstantsRemoved = jsonObj.toString();
}
The 2nd method that works by removing the entire JSONArray element and re-adding it to the JSONObject:
JSONObject jsonObj = new JSONObject(metadataOriginalJSON);
if (jsonObj.isJSONArray("Constants")) {
jsonObj.remove("Constants");
jsonObj.put("Constants", new JSONArray());
metadataConstantsRemoved = jsonObj.toString();
}