Android Json and null values

android, java, json

Solution

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

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

Problem

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 ```

Original source