getString與optString的區別
阿新 • • 發佈:2018-12-26
JSONObject.getString("key"):當物件中沒有key屬性的時候,會丟擲No value for "key"的異常;
public String getString(String name) throws JSONException { Object object = get(name); String result = JSON.toString(object); if (result == null) { throw JSON.typeMismatch(name, object, "String"); } return result; } public Object get(String name) throws JSONException { Object result = nameValuePairs.get(name); if (result == null) { throw new JSONException("No value for " + name); } return result; }
JSONObject.optString("key"):不會;
public String optString(String name) { return optString(name, ""); } public String optString(String name, String fallback) { Object object = opt(name); String result = JSON.toString(object); return result != null ? result : fallback; }