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

来源:互联网 发布:淘宝怎样注册小号 编辑:程序博客网 时间:2024/06/05 06:02
在JSONObject获取value有多种方法,如果key不存在的话,这些方法无一例外的都会抛出异常。如果在线环境抛出异常,就会使出现error页面,影响用户体验,针对这种情况最好是使用optXXX方法。

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

 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.");    }
getInt方法会抛出异常,如下所示:

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.");    }

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

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.");     }


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

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.");    }

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

public String optString(String key)    {        verifyIsNull();        return optString(key, "");    }
  public String optString(String key, String defaultValue)    {        verifyIsNull();        Object o = opt(key);        return o != null ? o.toString() : defaultValue;    }



0 0