In a JSON "object" (aka dictionary), there are two ways to represent absent values: Either have no key/value pair at all, or have a key with the JSON value null.
So you either use .add with a proper value what will get translated to null when you build the JSON, or you don't have the .add call.
Answer from gnasher729 on Stack ExchangeIn a JSON "object" (aka dictionary), there are two ways to represent absent values: Either have no key/value pair at all, or have a key with the JSON value null.
So you either use .add with a proper value what will get translated to null when you build the JSON, or you don't have the .add call.
It is a JSON-B design deficiency. They could have done something slick like:
Json.createObjectBuilder().addIfNotNull("address", this.getAddress());
Json.createObjectBuilder().add("address", this.getAddress(), defaultOnNull);
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".
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")
Use .has(String) and .isNull(String)
A conservative usage could be;
if (record.has("my_object_name") && !record.isNull("my_object_name")) {
// Do something with object.
}
It might be little late(it is for sure) but posting it for future readers
You can use JSONObject optJSONObject (String name) which will not throw any exception and
Returns the value mapped by name if it exists and is a JSONObject, or null otherwise.
so you can do
JSONObject obj = null;
if( (obj = result.optJSONObject("ERROR"))!=null ){
// it's an error , now you can fetch the error object values from obj
}
or if you just want to test nullity without fetching the value then
if( result.optJSONObject("ERROR")!=null ){
// error object found
}
There is whole family of opt functions which either return null or you can also use the overloaded version to make them return any pre-defined values.
e.g
String optString (String name, String fallback)
Returns the value mapped by name if it exists, coercing it if necessary, or fallback if no such mapping exists.
where coercing mean, it will try to convert the value into String type
A modified version of the @TheMonkeyMan answer to eliminate redundant look-ups
public void processResult(JSONObject result) {
JSONObject obj = null;
if( (obj = result.optJSONObject("ERROR"))!=null ){
//^^^^ either assign null or jsonobject to obj
// if not null then found error object , execute if body
String error_detail = obj.optString("DESCRIPTION","Something went wrong");
//either show error message from server or default string as "Something went wrong"
finish(); // kill the current activity
}
else if( (obj = result.optJSONObject("STATISTICS"))!=null ){
String stats = obj.optString("Production Stats");
//Do something
}
else
{
throw new Exception("Could not parse JSON Object!");
}
}
Right there in the documentation, in the first paragraph:
Values may not be
null,NaNs, infinities, or of any type not listed here.
So yes, it is "...something that null values are not included..." (edit: that was a quote from your original question; your updated question changes it to "uninitialized values" but the default value of an object reference is null, so...)
It's a "feature" of that class, though; JSON itself understands null just fine. Further down in the documentation it says you use a "sentinal value," NULL, to represent null. Which seems...odd. There's a note about it:
Warning: this class represents
nullin two incompatible ways: the standard Javanullreference, and the sentinel valueNULL. In particular, callingput(name, null)removes the named entry from the object butput(name, JSONObject.NULL)stores an entry whose value isJSONObject.NULL.
So:
params.put(KEY_TOKEN, token == null ? JSONObject.NULL : token);
According to RFC 4627, JSON treats the null symbol as a valid value.
The catch is that JSON null is the representation for the Javascript null value. By contrast, the Java version of null is (according to the experts) more closely aligned with Javascript's undefined value.
The original author of the org.json library decided that JSONObject should treat JSON null in a way that is consistent with the Javascript semantics. Hence it is represented (in Java) as JSONObject.NULL ... which is not equal to null.
Use the following method of JsonObject to check if a value against any key is null
public boolean isNull(java.lang.String key)
This method is used to check Null against any key or if there is no value for the key.
check this in the documentation
Your Modified code should be like this
if(jsonObject.isNull("parentId"))
{
System.out.println("inside null");
jsonObject.put("parentId", 0);
}
else
{
System.out.println("inside else part");
//jsonObject.put("parentId", jsonObject.getInt("parentId"));
jsonObject.put("parentId", 0);
}
if(jsonObject.isNull("parentId")){
jsonObject.put("parentId", 0);
}
You may find this more useful and natural
JSONObject.NULL.equals(jsonObj.get("key_name"))
Have a look at: http://grails.1312388.n4.nabble.com/The-groovy-truth-of-JSONObject-Null-td3661040.html
Ian Roberts mentions a nice trick to make a null check possible:
JSONObject.NULL.metaClass.asBoolean = {-> false}