首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >jsonObject.getString()与jsonObject.optString()「建议收藏」

jsonObject.getString()与jsonObject.optString()「建议收藏」

作者头像
全栈程序员站长
发布2022-09-28 10:51:39
发布2022-09-28 10:51:39
4.7K0
举报

大家好,又见面了,我是你们的朋友全栈君

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

代码语言:javascript
复制
	    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类部分源码:

代码语言:javascript
复制
    /** * 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的时候才会抛出异常。类型不会导致异常。

参考:jsonObject.getString()解析任意字段均可强转为string

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/193755.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022年9月2日 下,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一:optString与getString的区别:
  • 二:getString()可获取任意类型的数据?
  • JSONObject类部分源码:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档