Android Json和null值

Add*_*dev 90 java android json

如何检测json值何时为空?例如:[{"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));
Run Code Online (Sandbox Code Playgroud)

日志输出是

{"hello":"null","bye":null}
hello=null is null? false
bye=null is null? false
Run Code Online (Sandbox Code Playgroud)

K-b*_*llo 211

试试吧json.isNull( "field-name" ).

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

  • 我会更进一步说,永远不要使用has(KEY_NAME),将这些调用替换为!isNull(KEY_NAME). (4认同)

FTh*_*son 16

因为如果给定的键存在,JSONObject#getString返回一个值,根据定义它不是null.这就是JSONObject.NULL存在的原因:表示空JSON值.

json.getString("hello").equals(JSONObject.NULL); // should be false
json.getString("bye").equals(JSONObject.NULL); // should be true
Run Code Online (Sandbox Code Playgroud)


小智 14

对于android,如果不存在这样的映射,它将引发JSONException.所以你不能直接调用这个方法.

json.getString("bye")
Run Code Online (Sandbox Code Playgroud)

如果您的数据可以为空(可能不存在密钥),请尝试

json.optString("bye","callback string");
Run Code Online (Sandbox Code Playgroud)

要么

json.optString("bye");
Run Code Online (Sandbox Code Playgroud)

代替.

在你的演示代码中,

JSONObject json = new JSONObject("{\"hello\":null}");
json.getString("hello");
Run Code Online (Sandbox Code Playgroud)

你得到的是String"null"而不是null.

你的好意思

if(json.isNull("hello")) {
    helloStr = null;
} else {
    helloStr = json.getString("hello");
}
Run Code Online (Sandbox Code Playgroud)