我从MySQL数据库中提取了一些数据,其中一些字段为NULL。不是意外地作为字符串,而是正确地存储为NULL。当我将这些JSON编码的空数据发送到我的android应用程序时,它们最终是一个长度为4的字符串"null"。因此,我重新构建了这个问题,浓缩为基本代码:
PHP:
$string = null;
echo $array[0]['alt_names'] = $string;
echo json_encode($array);
Java:(我的PHP类返回一个字符串,在本例中为jsonResult
)
Log.i("Tag", "result = " + jsonResult); // result = [{"alt_names":null}]
JSONArray jsonArray = new JSONArray(jsonResult);
Log.i("Tag", "jsonArray = " + jsonArray); // jsonArray = [{"alt_names":null}]
JSONObject jsonObject = new JSONObject(jsonArray.getJSONObject(0).toString());
Log.i("Tag", "jsonobject = " + jsonObject); // jsonobject = {"alt_names":null}
String test = jsonObject.get("alt_names").toString();
Log.i("Tag", "test: " + test); // test: null
Log.i("Tag", "test.length(): " + test.length()); // test.length(): 4
日志输出中null
周围缺少的引号(不是)向我表明,这不是一个字符串"null",而实际上是null
。然而,字符串的长度是4,这是真的:
if (test.equals("null")) {Log.i("Tag", "true");} // true
我有什么不明白的?提前感谢!
不要对jsonObject.get("alt_names")
返回的对象执行toString()
。它实际上是JSONObject.NULL 的静态实例
Object test = jsonObject.get("alt_names");
System.out.println(test == JSONObject.NULL); // true
System.out.println(test.equals(null)); // true
System.out.println(jsonObject.isNull("alt_names")); // true
来自javadoc:
有时,使用NULL对象比使用Java的NULL值更方便,也不那么模糊。JSONObject.NULL.equals(NULL)返回true。JSONObject.NULL.toString()返回"NULL"。