[英]Handling JSONObject Exceptions
我正在使用JSONObject
构建JSON响应。 我面临的问题是如何处理.put()
引发的异常。 我用try catch包围了代码,但是我也想在catch中输出JSON。 我一直在手动执行此操作,如下所示,但这似乎容易出错。处理此异常的正确方法是什么?
try{
myResponse.put("successful",true);
resp.getOutputStream().print(myeResponse.toString());
} catch (JSONException e) {
resp.getOutputStream().print("{\"successful\":false, \"error\":\"Changes could not be saved. Please reload the page and try again.\"}");
}
您需要确定的是JSONObject
的put()
方法何时会抛出JSONException
。
public JSONObject put(java.lang.String key,
boolean value)
throws JSONException
Put a key/boolean pair in the JSONObject.
Parameters:
key - A key string.
value - A boolean which is the value.
Returns:
this.
Throws:
JSONException - If the key is null.
因此,您需要注意的是您的密钥不为null,这肯定是事实,因为您的密钥是"successful"
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.