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会在你的数据有问题的时候及时通知你,你的数据出现问题了,以方便我们去解决他

原创粉丝点击