Android Json and null values

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

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

For android it will raise an JSONException if no such mapping exists. So you can't call this method directly.

json.getString("bye")

if you data can be empty(may not exist the key), try

json.optString("bye","callback string");

or

json.optString("bye");

instead.

In your demo code, the

JSONObject json = new JSONObject("{\"hello\":null}");
json.getString("hello");

this you get is String "null" not null.

your shoud use

if(json.isNull("hello")) {
    helloStr = null;
} else {
    helloStr = json.getString("hello");
}

first check with isNull()....if cant work then try belows

and also you have JSONObject.NULL to check null value...

 if ((resultObject.has("username")
    && null != resultObject.getString("username")
    && resultObject.getString("username").trim().length() != 0)
      {
               //not null
        }

and in your case also check resultObject.getString("username").trim().eqauls("null")


If you must parse json first and handle object later, let try this

Parser

Object data = json.get("username");

Handler

if (data instanceof Integer || data instanceof Double || data instanceof Long) {
     // handle number ;
} else if (data instanceof String) {
     // hanle string;               
} else if (data == JSONObject.NULL) {
     // hanle null;                 
}