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.
JsonObject::clear() removes all members from the object pointed by the JsonObject . If the JsonObject is null, this function does nothing.
JSON has a special value called null which can be set on any type of data including arrays, objects, number and boolean types.
You can remove an element from the JSONArray object using the remove() method. This method accepts an integer and removes the element in that particular index.
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)
Iterator keys = detailJSON.keys();
while(keys.hasNext())
detailJSON.remove((String)detailJSON.keys().next());
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With