0

我正在使用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.\"}");
}
4

1 回答 1

4

你需要弄清楚的是什么时候throw的put()方法。JSONObjectJSONException

来自Javadoc

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.

因此,您需要注意的是您的密钥不为空,因为您的密钥是"successful".

于 2013-01-11T17:08:09.757 回答