json教程系列(4)-optXXX方法的使用

在JSONObject获取value有多种方法,如果key不存在的话,这些方法无一例外的都会抛出异常。如果在线环境抛出异常,就会使出现error页面,影响用户体验,针对这种情况最好是使用optXXX方法。

 1  public String getString(String key)
 2     {
 3         verifyIsNull();
 4         Object o = get(key);
 5         if (o != null)
 6         {
 7             return o.toString();
 8         }
 9         throw new JSONException("JSONObject[" + JSONUtils.quote(key) + "] not found.");
10     }
View Code

getInt方法会抛出异常,如下所示:

 1  public int getInt(String key)
 2     {
 3         verifyIsNull();
 4         Object o = get(key);
 5         if (o != null)
 6         {
 7             return o instanceof Number ? ((Number) o).intValue() : (int) getDouble(key);
 8         }
 9         throw new JSONException("JSONObject[" + JSONUtils.quote(key) + "] is not a number.");
10     }
View Code

getDouble方法会抛出异常,如下所示:    

 1 public double getDouble(String key)
 2     {
 3         verifyIsNull();
 4         Object o = get(key);
 5         if (o != null)
 6         {
 7             try
 8             {
 9                 return o instanceof Number ? ((Number) o).doubleValue() : Double.parseDouble((String) o);
10             }
11             catch (Exception e)
12             {
13                 throw new JSONException("JSONObject[" + JSONUtils.quote(key) + "] is not a number.");
14             }
15         }
16         throw new JSONException("JSONObject[" + JSONUtils.quote(key) + "] is not a number.");
17  
18     }
View Code

getBoolean方法会抛出异常,如下所示:   

 1 public boolean getBoolean(String key)
 2     {
 3         verifyIsNull();
 4         Object o = get(key);
 5         if (o != null)
 6         {
 7             if (o.equals(Boolean.FALSE) || (o instanceof String && ((String) o).equalsIgnoreCase("false")))
 8             {
 9                 return false;
10             }
11             else if (o.equals(Boolean.TRUE) || (o instanceof String && ((String) o).equalsIgnoreCase("true")))
12             {
13                 return true;
14             }
15         }
16         throw new JSONException("JSONObject[" + JSONUtils.quote(key) + "] is not a Boolean.");
17     }
View Code

JSONObject有很多optXXX方法,比如optBoolean,optString,optInt。它们的意思是,如果JsonObject有这个属性,则返回这个属性,否则返回一个默认值。下面以optString方法为例说明一下其底层实现过程:JSONObject有很多optXXX方法,比如optBoolean,optString,optInt。它们的意思是,如果JsonObject有这个属性,则返回这个属性,否则返回一个默认值。下面以optString方法为例说明一下其底层实现过程:

1     public String optString(String key)
2     {
3         verifyIsNull();
4         return optString(key, "");
5     }
View Code
1   public String optString(String key, String defaultValue)
2     {
3         verifyIsNull();
4         Object o = opt(key);
5         return o != null ? o.toString() : defaultValue;
6     }
View Code

 

posted @ 2017-03-23 21:53  奔跑8蜗牛  阅读(186)  评论(0编辑  收藏  举报