Android Json 和空值

如何检测 json 值是否为 null? 例如: < strong > [{“ username”: null } ,{“ username”: “ null”}]

第一种情况表示一个不存在的用户名,第二种情况表示一个名为“ null”的用户。但是如果你试图检索它们,两个值都会导致字符串“ 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));

日志输出为

{"hello":"null","bye":null}
hello=null is null? false
bye=null is null? false
94909 次浏览

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

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

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

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

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.