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.
detailJSON=new JSONObject();
should work. You seem to have a bug somewhere in your code.detailJSON=null;
must remove the reference to actual objectdetailJSON=new JSONObject();
must point to newly created object. Ater creating new object, populate with new values and check whether this works or not.