溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

JSON中optString和getString的區(qū)別是什么

發(fā)布時間:2021-08-13 17:32:41 來源:億速云 閱讀:264 作者:Leah 欄目:大數(shù)據(jù)

本篇文章為大家展示了JSON中optString和getString的區(qū)別是什么,內(nèi)容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細(xì)介紹希望你能有所收獲。

常見使用原生的解析json方法:

        JSONObject jsonObject = new JSONObject();

        String str1 = jsonObject.optString("6不6");

        String str2 = jsonObject.optString("6不6","默認(rèn)6");

        try {

            String str3 = jsonObject.getString("666");

        } catch (JSONException e) {

            e.printStackTrace();

        }

一:optString與getString的區(qū)別:

optString會在得不到你想要的值時候返回空字符串“ ”或指定的默認(rèn)值,而getString會拋出異常。

optString可以解決服務(wù)器字段缺少或者沒有該字段而導(dǎo)致的異常以至于程序崩潰。

推薦使用optString,可避免接口字段的缺失、value的數(shù)據(jù)類型轉(zhuǎn)換等異常。

二:getString()可獲取任意類型的數(shù)據(jù)?

先看JSONObject的源碼如下:

JSONObject類部分源碼:

    /**

     * 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);//任何類型強(qiáng)轉(zhuǎn)為string

        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, "");

    }

    /**

     * Returns the value mapped by {@code name} if it exists, coercing it if

     * necessary, or {@code fallback} if no such mapping exists.

     */

    public String optString(String name, String fallback) {

        Object object = opt(name);

        String result = JSON.toString(object);

        return result != null ? result : fallback;//不為空取結(jié)果,為空取指定值

    }

可以看到getString、optString任意類型的value在return之前都會被強(qiáng)轉(zhuǎn)為string類型, 

這也就是為什么一直用getString來獲取字段時從沒出現(xiàn)過數(shù)據(jù)類型異常的原因。

getString只有在沒有該字段或結(jié)果為null的時候才會拋出異常。類型不會導(dǎo)致異常。

上述內(nèi)容就是JSON中optString和getString的區(qū)別是什么,你們學(xué)到知識或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識儲備,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI