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)
堆栈跟踪 finally 调用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 评论),所有检查都是在创建对象时执行的,那么toString(int)
方法可能永远不会引发异常。
希望能帮助到你,