楚落凡尘

getString与optString的区别

JSONObject.getString("key"):当对象中没有key属性的时候,会抛出No value for "key"的异常;

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;
    }
public Object get(String name) throws JSONException {
        Object result = nameValuePairs.get(name);
        if (result == null) {
            throw new JSONException("No value for " + name);
        }
        return result;
    }

JSONObject.optString("key"):不会;

public String optString(String name) {
        return optString(name, "");
    }

public String optString(String name, String fallback) {
        Object object = opt(name);
        String result = JSON.toString(object);
        return result != null ? result : fallback;
    }

 

posted on 2018-12-26 15:45  楚落凡尘  阅读(3621)  评论(0编辑  收藏  举报

导航