optString和getString区别
来源:互联网 发布:单片机与智能门镜 编辑:程序博客网 时间:2024/04/25 10:02
解析网络JSON数据时,获取数据的两个方法optString和getString;
使用optString获取数据时,即使后台服务器没有发送这个字段过来,他也不会报JSONException异常;
getString获取的字段如果没有传过来,则会报JSONException异常。
在从源码上面分析这两个;
optString:
/** * 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; }
从源码中可已看出我们调用的时候,代码中执行了这一句
return result != null ? result : fallback;
fallback这个值是在我们调用的第一个方法传过去的""
;所以使用这个获取网络数据,即使数据中没有这个字段,它也会返回一个空值;
在来看getString():
/** * 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; }
这个方法中它抛出了一个异常,这个异常在从数据中取数据的时候,该字段的数据类型不匹配的时候抛出
if (result == null) { throw JSON.typeMismatch(name, object, "String"); } return result;
而我们的是JSONException这个异常,所以我们看这一句 Object object = get(name);中的get方法;
public Object get(String name) throws JSONException { Object result = nameValuePairs.get(name); if (result == null) { throw new JSONException("No value for " + name); } return result; }
这个方法中的值如果为空,又会给我们抛出一个异常JSONException,告诉我们它没有从数据中找到你要的字段,所以取不到值。
两个方法各有优点,optString这个方法不会因为你的数据中,少了几个字段,而崩溃或者数据显示不出来,它不会通知你数据有问题,getString会在你的数据有问题的时候及时通知你,你的数据出现问题了,以方便我们去解决他
阅读全文
0 0
- optString和getString区别
- Json中optString和getString的区别
- JSON中optString和getString的区别
- JSONObject的getString()和optString()的区别
- jsonObject.getString() 和jsonObject.optString()区别
- JSON中optString和getString的区别
- JSON中optString()和getString()区别
- JSON中optString和getString的区别
- getString和optString的区别(补充toString和valueOf)
- JSONObject optString与getString区别
- JsonObject的optString()和getString()的区别
- 关于JSON中optString和getString的区别
- JSONObject中optString和getString等的区别
- JSON中getString() 和optString()
- JSON中getString() 和optString()
- JSONobject.getString()和JSONobject.optString()
- 安卓解析中JSON中getString() 和optString()的区别
- JSONObject optString与getString
- leetcode521. Longest Uncommon Subsequence I
- Android 开机启动app
- 烦人的MikTeX
- Promise对象简介
- hibernate注解方法总结
- optString和getString区别
- 一些资料
- 常见排序算法的时间复杂度和空间复杂度对比表
- java之观察者模式
- 遗传算法(二)改进:自适应、遗传退火算法
- 高性能Mysql
- MySql学习之Join查询
- Oracle简单的存储过程+根据条件修改字段值
- POJ1163:The Triangle