json教程系列(4)-optXXX方法的使用
2017-03-11 09:13
459 查看
在JSONObject获取value有多种方法,如果key不存在的话,这些方法无一例外的都会抛出异常。如果在线环境抛出异常,就会使出现error页面,影响用户体验,针对这种情况最好是使用optXXX方法。
getString方法会抛出异常,如下所示:
getInt方法会抛出异常,如下所示:
getDouble方法会抛出异常,如下所示:
getBoolean方法会抛出异常,如下所示:
JSONObject有很多optXXX方法,比如optBoolean,optString,optInt。它们的意思是,如果JsonObject有这个属性,则返回这个属性,否则返回一个默认值。下面以optString方法为例说明一下其底层实现过程:
getString方法会抛出异常,如下所示:
1 2 3 4 5 6 7 8 9 10 | public String getString(String key) { verifyIsNull(); Object o = get(key); if (o != null) { return o.toString(); } throw new JSONException("JSONObject[" + JSONUtils.quote(key) + "] not found."); } |
1 2 3 4 5 6 7 8 9 10 | public int getInt(String key) { verifyIsNull(); Object o = get(key); if (o != null) { return o instanceof Number ? ((Number) o).intValue() : (int) getDouble(key); } throw new JSONException("JSONObject[" + JSONUtils.quote(key) + "] is not a number."); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | public double getDouble(String key) { verifyIsNull(); Object o = get(key); if (o != null) { try { return o instanceof Number ? ((Number) o).doubleValue() : Double.parseDouble((String) o); } catch (Exception e) { throw new JSONException("JSONObject[" + JSONUtils.quote(key) + "] is not a number."); } } throw new JSONException("JSONObject[" + JSONUtils.quote(key) + "] is not a number."); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | public boolean getBoolean(String key) { verifyIsNull(); Object o = get(key); if (o != null) { if (o.equals(Boolean.FALSE) || (o instanceof String && ((String) o).equalsIgnoreCase("false"))) { return false; } else if (o.equals(Boolean.TRUE) || (o instanceof String && ((String) o).equalsIgnoreCase("true"))) { return true; } } throw new JSONException("JSONObject[" + JSONUtils.quote(key) + "] is not a Boolean."); } |
1 2 3 4 5 | public String optString(String key) { verifyIsNull(); return optString(key, ""); } |
1 2 3 4 5 6 | public String optString(String key, String defaultValue) { verifyIsNull(); Object o = opt(key); return o != null ? o.toString() : defaultValue; } |
相关文章推荐
- json教程系列(4)-optXXX方法的使用
- json学习系列(4)-JSONString对象的optXXX方法的使用
- Struts1.x系列教程(18):使用DispatchAction类调用多个Action方法
- mysqlsla慢查询分析工具安装使用方法 - ttlsa教程系列之mysql
- json教程系列(2)-生成JSONObject的方法
- Json数据格式的使用方法入门教程
- WPF入门系列教程(二) 深入剖析WPF Binding的使用方法(上)
- Struts1.x系列教程(21):使用MappingDispatchAction类调用不同的Action方法
- 使用ASP.NET Web Api构建基于REST风格的服务实战系列教程【五】——在Web Api中实现Http方法(Put,Post,Delete)
- WPF入门教程系列(二) 深入剖析WPF Binding的使用方法
- WPF入门教程系列(二) 深入剖析WPF Binding的使用方法
- WPF入门系列教程(二) 深入剖析WPF Binding的使用方法
- WPF入门教程系列(二) 深入剖析WPF Binding的使用方法(下)
- WPF入门教程系列(二) 深入剖析WPF Binding的使用方法
- Struts1.x系列教程(18):使用DispatchAction类调用多个Action方法
- Ollydbg使用教程系列-中断方法浅探
- Struts1.x系列教程(21):使用MappingDispatchAction类调用不同的Action方法
- android fastjson使用方法 fastjson教程
- Cocos2d-x教程(24)-rapidJson使用方法
- springBoot系列教程05:fastjson的集成、配置及使用