最近在写任务时,使用JSONObject.getString(key)这个方法时一遇到空值就报错,在网上简单查了一下原因。
JSONObject中getString和optString作用大致是相同的
通过下面的源码我们可以发现,getString通过key获取value时,如果值为空,则会报错并抛出异常。
而在optString中不管获取的值是不是为空,则会直接返回一个空字符串,并且如果当前的类型不少字符串,则会自动转换成字符串,当然也可以通过方法设置一个默认的返回值。
因此综上所述,我们在获取键值时尽量使用optString()这个方法。
/**
* Get the string associated with a key.//获取与键相关联的字符串。
*
* @param key
* A key string.
* @return A string which is the value.
* @throws JSONException
* if there is no string value for the key.
*/
public String getString(String key) throws JSONException {
Object object = this.get(key);
if (object instanceof String) {
return (String) object;
}
throw wrongValueFormatException(key, "string", null);
}
/**
* Get an optional string associated with a key. It returns an empty string
* if there is no such key. If the value is not a string and is not null,
* then it is converted to a string.
*获取与键关联的可选字符串。如果没有这样的键,则返回空字符串。如果该值不是字符串,
*也不是null,则将其转换为字符串。
* @param key
* A key string.
* @return A string which is the value.
*/
public String optString(String key) {
return this.optString(key, "");
}
/**
* Get an optional string associated with a key. It returns the defaultValue
* if there is no such key.
*
* @param key
* A key string.
* @param defaultValue
* The default.
* @return A string which is the value.
*/
public String optString(String key, String defaultValue) {
Object object = this.opt(key);
return NULL.equals(object) ? defaultValue : object.toString();
}