温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

JSON中optString和getString的区别是什么

发布时间:2021-08-13 17:32:41 来源:亿速云 阅读:255 作者:Leah 栏目:大数据

本篇文章为大家展示了JSON中optString和getString的区别是什么,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

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

        JSONObject jsonObject = new JSONObject();

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

        String str2 = jsonObject.optString("6不6","默认6");

        try {

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

        } catch (JSONException e) {

            e.printStackTrace();

        }

一:optString与getString的区别:

optString会在得不到你想要的值时候返回空字符串“ ”或指定的默认值,而getString会抛出异常。

optString可以解决服务器字段缺少或者没有该字段而导致的异常以至于程序崩溃。

推荐使用optString,可避免接口字段的缺失、value的数据类型转换等异常。

二:getString()可获取任意类型的数据?

先看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);//任何类型强转为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;//不为空取结果,为空取指定值

    }

可以看到getString、optString任意类型的value在return之前都会被强转为string类型, 

这也就是为什么一直用getString来获取字段时从没出现过数据类型异常的原因。

getString只有在没有该字段或结果为null的时候才会抛出异常。类型不会导致异常。

上述内容就是JSON中optString和getString的区别是什么,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI