Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Json and null values

Tags:

java

json

android

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 
like image 526
Addev Avatar asked May 14 '12 18:05

Addev


People also ask

Can JSON store null values?

JSON has a special value called null which can be set on any type of data including arrays, objects, number and boolean types.

How check JSON object is null or not in android?

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

How do you handle a null response in JSON?

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 create a JSON 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.


2 Answers

Try with json.isNull( "field-name" ).

Reference: http://developer.android.com/reference/org/json/JSONObject.html#isNull%28java.lang.String%29

like image 50
K-ballo Avatar answered Oct 16 '22 08:10

K-ballo


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 
like image 35
FThompson Avatar answered Oct 16 '22 06:10

FThompson