Android开发之Json解析是getInt()和optInt()的区别

Json解析的时候有两种方式根据Key的值获取对应的Value:

一种是get,一种是opt:,

先看optInt的源码:

public int optInt(int index) {
        return optInt(index, 0);
    }

    /**
     * Returns the value at {@code index} if it exists and is an int or
     * can be coerced to an int. Returns {@code fallback} otherwise.
     */
public int optInt(int index, int fallback) {
      Object object = opt(index);
      Integer result = JSON.toInteger(object);
      return result != null ? result : fallback;
  }

 主要是看有两个参数的方法,当根据当找不到当前给的key的时候,会使用fallback中的值作为value返回。 

 

下面是getInt的源码:

public int getInt(String name) throws JSONException {
        Object object = get(name);
        Integer result = JSON.toInteger(object);
        if (result == null) {
            throw JSON.typeMismatch(name, object, "int");
        }
        return result;
    }

  getInt方法在找不到对应的key的时候会抛异常。

 

posted @ 2017-02-28 13:07  Godfunc  阅读(1869)  评论(0编辑  收藏  举报