解析 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 = "";