I have some data extracted from a MySQL database where some fields are NULL . Not accidentally as a string but properly stored as NULL . When I send these null-data JSON-encoded to my android app, they end up being a string "null" of length 4. So I rebuilt this problem condensed to the essential code:
PHP:
$string = null;
echo $array[0]['alt_names'] = $string;
echo json_encode($array);
Java: (My PHP class returns a string, in this case 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
The missing quotation marks (not) enclosing null
in the Log-output show me, that this is not a string "null" butt actually null
. Nevertheless the string's length is 4 and this is true:
if (test.equals("null")) {Log.i("Tag", "true");} // true
What do I not understand? Thanks in advance!
Don't do a toString()
on the object return by jsonObject.get("alt_names")
. It is actually the static instance of 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
From javadoc :
It is sometimes more convenient and less ambiguous to have a NULL object than to use Java's null value. JSONObject.NULL.equals(null) returns true. JSONObject.NULL.toString() returns "null".
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.