解析 json 时使用空字符串
{
"some_string": null,
"ather_string": "something"
}
如果我们将这样使用:
JSONObject json = new JSONObject(jsonStr);
String someString = json.optString("some_string");
我们将有输出:
someString = "null";
所以我们需要提供这个解决方法:
/**
* According to http://stackoverflow.com/questions/18226288/json-jsonobject-optstring-returns-string-null
* we need to provide a workaround to opt string from json that can be null.
* <strong></strong>
*/
public static String optNullableString(JSONObject jsonObject, String key) {
return optNullableString(jsonObject, key, "");
}
/**
* According to http://stackoverflow.com/questions/18226288/json-jsonobject-optstring-returns-string-null
* we need to provide a workaround to opt string from json that can be null.
* <strong></strong>
*/
public static String optNullableString(JSONObject jsonObject, String key, String fallback) {
if (jsonObject.isNull(key)) {
return fallback;
} else {
return jsonObject.optString(key, fallback);
}
}
然后调用:
JSONObject json = new JSONObject(jsonStr);
String someString = optNullableString(json, "some_string");
String someString2 = optNullableString(json, "some_string", "");
我们将按预期输出:
someString = null; //not "null"
someString2 = "";