How can I detect when a json value is null? for example: [{"username":null},{"username":"null"}]
The first case represents an unexisting username and the second a user named "null". But if you try to retrieve them both values result in the string "null"
JSONObject json = new JSONObject("{\"hello\":null}"); json.put("bye", JSONObject.NULL); Log.e("LOG", json.toString()); Log.e("LOG", "hello="+json.getString("hello") + " is null? " + (json.getString("hello") == null)); Log.e("LOG", "bye="+json.getString("bye") + " is null? " + (json.getString("bye") == null));
The log output is
{"hello":"null","bye":null} hello=null is null? false bye=null is null? false
JSON has a special value called null which can be set on any type of data including arrays, objects, number and boolean types.
Try with json. isNull( "field-name" ) . I would go further and say to NEVER use has(KEY_NAME), replacing those calls to ! isNull(KEY_NAME).
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.
If you want to represent a null value in JSON, the entire JSON string (excluding the quotes containing the JSON string) is simply null . No braces, no brackets, no quotes.
Try with json.isNull( "field-name" )
.
Reference: http://developer.android.com/reference/org/json/JSONObject.html#isNull%28java.lang.String%29
Because JSONObject#getString returns a value if the given key exists, it is not null by definition. This is the reason JSONObject.NULL exists: to represent a null JSON value.
json.getString("hello").equals(JSONObject.NULL); // should be false json.getString("bye").equals(JSONObject.NULL); // should be true
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