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

JavaJson

Java Problem Overview


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

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

For me with net.sf.json.JSONObject I need to create a null JSON by

new JSONObject(true)

This is how I get class into groovy:

groovy.grape.Grape.grab(group: "org.kohsuke.stapler", module: "json-lib", version: "2.4-jenkins-2")

Solution 3 - Java

I created this project https://github.com/leonardofel/JSON-java-put-null-fix

To change (or fix), just import the library to your pom.xml

this is how your code will behave:

JSONObject o = new JSONObject();
o.put("key", null);
o.isNull("key"); // returns true
o.has("key"); // returns true
o.isNull("somethingIHaventSetAtAll"); // returns true
o.get("key"); // returns null

o.remove("key");
o.isNull("key"); // returns true
o.has("key"); // returns false
o.isNull("somethingIHaventSetAtAll"); // returns true
o.get("key"); // throws JSONException "key" not found

Solution 4 - Java

Create a Utility Class or if you already have an existing one just create this utility method in it.

 class JsonObjectUtility{
           public static Object getJSONObjectValue(Object value)  {
	          return value == null ? "null" : value;
           }
 }

then pass all input through this utility before passing it to the JSONObject put method as below: (i will use the code sample in the question)

JSONObject o = new JSONObject();
o.put("key", JsonObjectUtility.getJSONObjectValue(null) );

This shall print a json string as below

> { "key" : null }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionB TView Question on Stackoverflow
Solution 1 - JavarekireView Answer on Stackoverflow
Solution 2 - JavaakostadinovView Answer on Stackoverflow
Solution 3 - JavaLeonardo LopesView Answer on Stackoverflow
Solution 4 - JavaWinter MCView Answer on Stackoverflow