如何检测 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));
日志输出为
{"hello":"null","bye":null}
hello=null is null? false
bye=null is null? false
has(java.lang.String);
方法。 - Blundell