toString() 方法不会引发异常,因为它必须覆盖 public void toString() 方法的签名 java.lang.Object。在org.json.JSONObject 泛型toString() 方法实际上默默地失败了,因为源代码是:
/**
* Make a JSON text of this JSONObject. For compactness, no whitespace is
* added. If this would not result in a syntactically correct JSON text,
* then null will be returned instead.
* <p>
* Warning: This method assumes that the data structure is acyclical.
*
* @return a printable, displayable, portable, transmittable representation
* of the object, beginning with <code>{</code> <small>(left
* brace)</small> and ending with <code>}</code> <small>(right
* brace)</small>.
*/
public String toString() {
try {
return this.toString(0);
} catch (Exception e) {
return null;
}
}
这个方法依赖于toString(int)方法,如果它抛出异常,它会捕获它并返回null。
根据toString(int) 的描述,当org.json.JSONObject 的其中一个元素中包含无效数字时,将引发异常;但是查看代码可能是由于其他原因引发了此异常。
当你使用toString(int)堆栈跟踪最终调用write()方法来解析对象本身时,从json对象到字符串的一些转换可能会抛出异常:
static final Writer writeValue(Writer writer, Object value,
int indentFactor, int indent) throws JSONException, IOException {
if (value == null || value.equals(null)) {
writer.write("null");
} else if (value instanceof JSONObject) {
((JSONObject) value).write(writer, indentFactor, indent);
} else if (value instanceof JSONArray) {
((JSONArray) value).write(writer, indentFactor, indent);
} else if (value instanceof Map) {
new JSONObject((Map<String, Object>) value).write(writer, indentFactor, indent);
} else if (value instanceof Collection) {
new JSONArray((Collection<Object>) value).write(writer, indentFactor,
indent);
} else if (value.getClass().isArray()) {
new JSONArray(value).write(writer, indentFactor, indent);
} else if (value instanceof Number) {
writer.write(numberToString((Number) value));
} else if (value instanceof Boolean) {
writer.write(value.toString());
} else if (value instanceof JSONString) {
Object o;
try {
o = ((JSONString) value).toJSONString();
} catch (Exception e) {
throw new JSONException(e);
}
writer.write(o != null ? o.toString() : quote(value.toString()));
} else {
quote(value.toString(), writer);
}
return writer;
}
但是,如果正如您在问题(和@Carlos Rodriguez cmets)中所说的那样,所有检查都是在创建对象时执行的,那么toString(int) 方法可能永远不会引发异常。
希望对你有帮助,