将HttpServletResponse转换为json

时间:2016-10-14 16:56:48

标签: java json spring-boot

我有以下ExceptionHandler:

@ExceptionHandler(ValueNotAllowedException.class)
void handleBadRequests(HttpServletResponse response, ValueNotAllowedException ex) throws IOException {
    response.sendError(HttpStatus.BAD_REQUEST.value(), ex.getMessage());
}

响应的类型为HTMLenter image description here 如何轻松地将响应转换为smth:

(来自项目中另一个控制器的响应。我的回答应该类似)

{
  "timestamp": 1476462787425,
  "status": 400,
  "error": "Bad Request",
  "exception": "org.springframework.http.converter.HttpMessageNotReadableException",
  "message": "Could not read document: Start date should be before or equal end date\n at [Source: java.io.PushbackInputStream@47842b65; line: 23, column: 16] (through reference chain: com.instinctools.mailtracker.endpoints.dto.QueryFilterDTO[\"startDate\"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Start date should be before or equal end date\n at [Source: java.io.PushbackInputStream@47842b65; line: 23, column: 16] (through reference chain: com.instinctools.mailtracker.endpoints.dto.QueryFilterDTO[\"startDate\"])",
  "path": "/statistics/clicks"
}

1 个答案:

答案 0 :(得分:2)

创建一个基础Error对象(正确注释),该对象将返回UI

class Error {
  private String timestamp;
  private Integer status;
  private String error;
  private String exception;
  private String message;
  private String path;

  //constructors here, whatever
 .....
}

..然后用这样的东西改变你的ExceptionHandler:

@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(ValueNotAllowedException.class)
@ResponseBody Error handleBadRequest(HttpServletRequest req, Exception ex) {
    //Create and return your Error object here. 
    return new Error(/* populate with all the stuff you need here */);
} 

希望这有帮助!