Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you set a value to null with org.json.JSONObject in java?

Tags:

java

json

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 
like image 927
B T Avatar asked Nov 28 '12 20:11

B T


People also ask

How do you handle a null value in JSON response in Java?

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.

How do I change the value of a JSONObject?

JSONObject js = new JSONObject(); js. put("name", "rai"); js. remove("name"); js. put("name", "abc");

Is null valid value in JSON?

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”.


1 Answers

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".

like image 84
rekire Avatar answered Oct 12 '22 04:10

rekire