ServletResponse でエラーメッセージを JSON で返す

API のレスポンスなど、エラーメッセージをJSON形式で出力する方法。

    JSONObject json = new JSONObject();
    json.put("error", "Error Message.");

    servletResponse.setStatus(403);
    servletResponse.setContentType("application/json; charset=utf8");
    OutputStream out = null;
    InputStream in = null;
    try {
      out = servletResponse.getOutputStream();
      in = new ByteArrayInputStream(json.toString()getBytes("UTF-8"));
      int b;
      while ((b = in.read()) != -1) {
        out.write(b);
      }
      out.flush();
    } catch (Throwable t) {
      LOG.log(Level.WARNING, t.getMessage(), t);
    } finally {
      IOUtils.closeQuietly(out);
      IOUtils.closeQuietly(in);
    }