How to set null value in org.json.JSONObject in java?

How to set null value in org.json.JSONObject in java? I can of course read if the value is null using isNull - but it seems that when I put null, it just ignores me:

JSONObject o = new JSONObject(); o.put("key",null); o.isNull("key"); // returns true, buuuut... o.has("key"); // returns false o.isNull("somethingIHaventSetAtAll"); // also returns true, unfortunately 
+55
java json
Nov 28 '12 at 20:24
source share
1 answer

Try setting JSONObject.NULL instead of null :

A sentinel value used to explicitly identify a name without a value. Unlike null, names with this value:

  • displayed in names () array
  • displayed in () iterator keys
  • return true for has (String)
  • don't throw get (String)
  • included in the JSON encoded string.

This value violates the general equals (Object) contract, returning true compared to null. Its toString () method returns "null".

+132
Nov 28 '12 at 20:27
source share



All Articles