Is there any way I can clear all JSONObject - java

I need to populate a json object this way, let it be called detailJSON:

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

I do like this:

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

After that, the detail is entered into some general settings, and now I want to clear this JSONObject and use the same detailJSON object to store another json (with different keys), as follows:

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

I know that there is a method, remove (), which removes a specific 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 many keys, so using remove actually increases the LOC. In addition, every time before deleting, I need to check if JSONObject has specific key or not.

Is there any other way I can implement JSONObject cleanup ??

I tried

 detailJSON=null ; detailJSON=new JSONObject(); 

But that will not work.

I'm basically looking for something like the clear () method, if one exists.

+6
source share
5 answers
 Iterator keys = detailJSON.keys(); while(keys.hasNext()) detailJSON.remove(keys.next().toString()); 
+1
source

if detailJSON is a map variable, you can use the detailJSON.clear() method for empty values ​​on the map.

+1
source

You could, but it will be a hack.

 Iterator i = detailJSON.keys(); while(i.hasNext()) { i.next().remove(); } //or detailJSON.keySet().clear(); 

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

Returns the Set view for keys contained in this map. The set is supported by the map, so changes in the map are reflected in the set and vice versa.

Java 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)

+1
source

you can use this method

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

This version has overhead due to receiving a set of keys every time, but it works without exception to parallel modifications.

 while(json.length()>0) json.remove(json.keys().next()); 
+1
source

All Articles