I want to remove any JSON key/value pairs wherein the value is the empty string ""
or is the string literal null
. However Java enumerations don't like that and will throw a ConcurrentModificationException
if you attempt to remove the key and value.
JSONArray ja = loadJSONArray();
JSONObject firstJSON = ja.getJSONObject(0);
Iterator<?> iter = firstJSON.keys();
for (int i = 0; i < ja.length(); i++) {
JSONObject json = ja.getJSONObject(i);
while (iter.hasNext()) {
String key = iter.next().toString();
if (json.getString(key).equals("null")) {
json.remove(key);
}
}
}
Output:
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.LinkedHashMap$LinkedHashIterator.nextNode(LinkedHashMap.java:711)
at java.util.LinkedHashMap$LinkedKeyIterator.next(LinkedHashMap.java:734)
at JSONKeyRemover.removeKeyWhileIterating(JSONKeyRemover.java:32)
at JSONKeyRemover.main(JSONKeyRemover.java:69)
I ended up copying the JSON array into a Java collection and used the JSONObject.names()
method to obtain a JSONArray
of keys.
JSONArray nameArray = firstJSON.names();
List<String> keyList = new ArrayList<String>();
for (int i = 0; i < nameArray.length(); i++) {
keyList.add(nameArray.get(i).toString());
}
for (int i = 0; i < ja.length(); i++) {
for (String key : keyList) {
JSONObject json = ja.getJSONObject(i);
if (json.getString(key).equals("null")) {
json.remove(key);
}
}
}
Output:
Before
[
{
"badid": "null",
"goodid": "1"
},
{
"badid": "2",
"goodid": "3"
}
]
After
[
{"goodid": "1"},
{
"badid": "2",
"goodid": "3"
}
]