12

I have to populate a json object like this, let say it is named detailJSON:

{"amount": "5.00", "ac_no": "123456" } 

I do it this way:

detailJSON.put("amount","5.00");
detailJSON.put("ac_no","123456");

After this, the detail is entered in some shared preferences, and now I want to clear this JSONObject and use the same detailJSON object to store another json (with different keys), this way:

{"amount":"6.00", "loan_no":"123456"}

I know there is a method, remove(), that removes the particular key and corresponding value.

This works:

detailJSON.remove("amount");
detailJSON.remove("ac_no");

and then use it --

detailJSON.put("amount","6.0");
detailJSON.put("loan_no","123456");

Now this is a very simple example. In the code I'm working on, I have a lot of keys, so using remove actually increases the LOC. Also, each time before removing I need to check whether JSONObject has that particular key or not.

Is there any other way, I can implement clearing of the JSONObject??

I tried

detailJSON=null ;
detailJSON=new JSONObject();

But it does not work.

I am basically in search of something like clear() method, if exists.

7
  • 1
    Are you sure you need to do that? Why not use a fresh JSONObject every time? I think it would be more costly to remove every single field than just creating a new one.
    – Uwe Allner
    Jul 6, 2015 at 7:23
  • @UweAllner I too totally agree with you but this is the business constraint, to maintain such a structure. Jul 6, 2015 at 7:25
  • 1
    detailJSON=new JSONObject(); should work. You seem to have a bug somewhere in your code.
    – Philipp
    Jul 6, 2015 at 7:25
  • detailJSON=null; must remove the reference to actual object detailJSON=new JSONObject(); must point to newly created object. Ater creating new object, populate with new values and check whether this works or not. Jul 6, 2015 at 7:28
  • okay, this should have worked, but thing is like this. I'm passing the detailJSON to the function, where this work is done, so here if I create the new json object it is the local variable, hence it does not work. Whereas remove work on the original reference. Jul 6, 2015 at 7:33

8 Answers 8

6
Iterator keys = detailJSON.keys();
while(keys.hasNext())
  detailJSON.remove((String)detailJSON.keys().next());
4
  • This is giving compilation error -- Can only iterate over an array or an instance of java.lang.Iterable in the line detailJSON.keys(). detailJSON is an instance of JSONObject. Jul 6, 2015 at 7:27
  • 1
    Well after you edited, this works, I had to cast to String though -- detailJSON.remove((String)detailJSON.keys().next()); Jul 6, 2015 at 7:36
  • But it's basically the same as detailJSON.remove("amount"); even worse, it will creates Iterator twice per loop. First to determine is there are any more elements, and after that, to get the next element.
    – dkiselev
    Jul 6, 2015 at 7:42
  • 8
    this will throw ConcurrentModificationException Jan 27, 2017 at 15:12
5

this version has an overhead because of getting the key-set everytime, but it works without concurrent modification exception.

while(json.length()>0)
   json.remove(json.keys().next());
2

You could, but it will be a hack.

Iterator i = detailJSON.keys();
while(i.hasNext()) {
    i.next().remove();
}

//or

detailJSON.keySet().clear();

It works, because JSONObject.keySet() will return you this.map.keySet(). And what JavaDoc for HashMap.keySet() said:

Returns a Set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa.

Java's HashMap from collections will return you java.util.HashMap.KeySet and java.util.HashMap.KeySet.clear(); just calls map.clear() (KeySet is an inner class of java.util.HashMap)

4
  • detailJSON.keySet().clear(); does not work, it gives this compilation error -- ` The method keySet() is undefined for the type JSONObject`. Trying the first solution now Jul 6, 2015 at 7:39
  • The first one also gives an error, to add the type cast to iterator, having done that, it gives run time error. Jul 6, 2015 at 7:43
  • Whch JSONObject do you use. I've tested this approach with snippet pastebin.com/SBDR3iaB
    – dkiselev
    Jul 6, 2015 at 7:48
  • Here is what I've used org.json.JSONObject.keySet() grepcode.com/file/repo1.maven.org/maven2/org.json/json/20141113/…
    – dkiselev
    Jul 6, 2015 at 8:18
1

you can use this method

public HashMap clearMap(HashMap detailJSON){
  for(String key: detailJSON.keySet())
    detailJSON.remove(key);
  return detailJSON;
}
0

if detailJSON is an map variable, the you can use detailJSON.clear() method to empty values in the map.

3
  • it is JSONObject variable. Jul 6, 2015 at 7:28
  • then detailJSON = new JSONObject() should remove all your previous data and will put and empty detailJSON object for you Jul 6, 2015 at 7:30
  • detailJSON = new JSONObject() would not work if detailJSON is declared as final, so that comment only refers to a specific usecase.
    – Daniel F
    Nov 25, 2016 at 10:57
0

It appears there is no clear method for JSONObject :. if you have to iterate all the JSONObject to clear it, better you get the parent node, and update with a new JSONObject().

You probably using while to get those details, so you can do this:

Iterator keys = mJson.keys();
while(keys.hasNext())
{
    String key = keys.next();
    JSONObject detailJSON = mJson.getJSONObject(key);
    JSONObject newDetail = new JSONObject();
    ...
    mJson.put(key,newDetail);
}

And when using JSONArray:

for (int i=0; i < mJson.length(); i++)
{
    JSONObject detailJSON = mJson.getJSONObject(i);
    JSONObject newDetail = new JSONObject();
    ...
    mJson.put(i,newDetail);
}
0

ConcurrentModificationException Proof 🔫

Directly using key set iterator of a JSONObject inside a loop for removing items will cause throw ConcurrentModificationException.

This is because when you remove an element, the JSONObject automatically modifies its key set that you are using inside the loop at the moment. And this's a violation!

One solution is to copy keys to an array first, then use the array instead of the iterator itself, like below :

public static void clearJson(JSONObject json) {
    if (json.length() > 0) {
        String[] keysArr = new String[json.length()];

        int counter = 0;
        for (Iterator<String> iter = json.keys();iter.hasNext();)
            keysArr[counter++] = iter.next();

        for (String key : keysArr)
            json.remove(key);
    }
}
0

you could re-declare the variable

JSONObject detailJSON= new JSONObject();

detailJSON.put("amount","5.00");
detailJSON.put("ac_no","123456");

detailJSON = new JSONObject()
1
  • 2
    Perhaps you mean re assign?
    – Suraj Rao
    Apr 16, 2022 at 6:20

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.