How do you set a value to null with org.json.JSONObject in java? I can certainly read if a value is null by using isNull - but it seems like 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
You can ignore null fields at the class level by using @JsonInclude(Include. NON_NULL) to only include non-null fields, thus excluding any attribute whose value is null. You can also use the same annotation at the field level to instruct Jackson to ignore that field while converting Java object to json if it's null.
JSONObject js = new JSONObject(); js. put("name", "rai"); js. remove("name"); js. put("name", "abc");
One of the changes in RFC 7159 is that a JSON text is not defined as being an object or an array anymore but rather as being a serialized value. This means that with RFC 7159, “null” (as well as “true” and “false”) becomes a valid JSON text. So the JSON text serialized value of a null object is indeed “null”.
Try to set JSONObject.NULL
instead of null
:
A sentinel value used to explicitly define a name with no value. Unlike null, names with this value:
- show up in the names() array
- show up in the keys() iterator
- return true for has(String)
- do not throw on get(String)
- are included in the encoded JSON string.
This value violates the general contract of equals(Object) by returning true when compared to null. Its toString() method returns "null".
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