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;
    }

猜你喜欢

转载自www.cnblogs.com/chuluofanchen/p/10179526.html