1. 程式人生 > >org.json.JSONObject的getString和optString使用註意事項

org.json.JSONObject的getString和optString使用註意事項

pts bubuko mapped 使用 necessary inf gets str 分享

結論:org.json.JSONObject的getString如果取不到對應的key會拋出異常,optString則不會

/**
     * Returns the value mapped by {@code name} if it exists, coercing it if
     * necessary, or throws if no such mapping exists.
     *
     * @throws JSONException if no such mapping exists.
     */
    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; } /** * Returns the value mapped by {@code name} if it exists, coercing it if * necessary, or the empty string if no such mapping exists.
*/ public String optString(String name) { return optString(name, ""); }

技術分享圖片

技術分享圖片

org.json.JSONObject的getString和optString使用註意事項