100

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
2
  • 1
    Do you control the JSON? Then don't send the username field and use the has(java.lang.String); method Commented May 14, 2012 at 18:16
  • 2
    This is a known and intentional bug: code.google.com/p/android/issues/detail?id=13830 Commented Sep 21, 2012 at 8:39

6 Answers 6

229

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

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

Sign up to request clarification or add additional context in comments.

3 Comments

I would go further and say to NEVER use has(KEY_NAME), replacing those calls to !isNull(KEY_NAME).
@SkyKelsey: Why would you say that? Those are different things with different semantics...
You're right. What I meant was that most of the time you use has(), you really would rather us !isNull(). Most of the time you are checking to see if a value exists at the key specified, and that is better accomplished with !isNull().
19

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

3 Comments

Thanks for your answer but imho and since an JSONException is thrown if the key don't exists is more logical returning null when the item is null
You'll need to take up stylistic preferences with the developers of the library itself :p
"null" != null. The problem is that isNull needs api 9+ and sometimes you want lower apis to work. This answer is well, you can use jsonObject.getString != "null" to.
16

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");
}

Comments

4

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

1 Comment

Simplified as "if(!resultObject.isNull("username") && resultObject.getString("username").trim().length() != 0)"
3

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;                 
}

Comments

2

Here's a helper method I use so that I can get JSON strings with only one line of code:

public String getJsonString(JSONObject jso, String field) {
    if(jso.isNull(field))
        return null;
    else
        try {
            return jso.getString(field);
        }
        catch(Exception ex) {
            LogHelper.e("model", "Error parsing value");
            return null;
        }
}

and then something like this:

String mFirstName = getJsonString(jsonObject, "first_name");

would give you your string value or safely set your string variable to null. I use Gson whenever I can to avoid pitfalls like these. It handles null values much better in my opinion.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.