JSONObject的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的源码如下:

`
/**
* 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的时候才会抛出异常。类型不会导致异常。
————————————————
原文链接:https://blog.csdn.net/sinat_31057219/article/details/77962305

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值