Android Json and null values

JavaAndroidJson

Java Problem Overview


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

Java Solutions


Solution 1 - Java

Solution 2 - Java

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

Solution 3 - Java

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

Solution 4 - Java

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

Solution 5 - Java

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

Solution 6 - Java

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAddevView Question on Stackoverflow
Solution 1 - JavaK-balloView Answer on Stackoverflow
Solution 2 - JavaFThompsonView Answer on Stackoverflow
Solution 3 - JavaShuaiView Answer on Stackoverflow
Solution 4 - JavaSamir MangroliyaView Answer on Stackoverflow
Solution 5 - Javathanhbinh84View Answer on Stackoverflow
Solution 6 - JavaLou MordaView Answer on Stackoverflow