【发布时间】:2020-05-10 03:38:31
【问题描述】:
我对 Spring 框架还很陌生,我正在尝试通过开发示例项目来学习
也许这是一个愚蠢的问题,但我根本找不到任何帮助。
当验证规则未通过时,我的控制器使用转义字符串而不是对象的 json 表示来响应请求。我使用 bean 验证器和 Gson 来生成错误的错误 json 表示。
我的控制器响应:
"{\"firstName\":\"firstName required\",\"lastName\":\"lastName required\",\"password\":\"password required\",\"matchingPassword\": \"matchingPassword required\",\"email\":\"email required\"}"
但在控制台中,Gson 会打印出正确的 json 表示
{"firstName":"firstName required","lastName":"lastName required","password":"password required","matchingPassword":"matchingPassword required","email":"email required"}
这是我的控制器:
@RequestMapping(value = "/user/registration", method = RequestMethod.POST, headers = "Accept=application/json", produces = {"application/json"})
public ResponseEntity<String> registerUserAccount(@Valid @RequestBody UserDTO accountDto) {
LOGGER.debug("Registering user account with information: {}", accountDto);
User registered = userService.registerNewUserAccount(accountDto);
return new ResponseEntity<>("Success", HttpStatus.OK);
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity handleValidationExceptions(MethodArgumentNotValidException ex) {
LOGGER.debug("MethodArgumentNotValidException called");
Map<String, String> errors = new HashMap<>();
ex.getBindingResult().getAllErrors().forEach((error) -> {
String fieldName = ((FieldError) error).getField();
String errorMessage = error.getDefaultMessage();
errors.put(fieldName, errorMessage);
});
Gson gson = new Gson();
LOGGER.debug(gson.toJson(errors));
return ResponseEntity.badRequest().contentType(MediaType.APPLICATION_JSON).body(gson.toJson(errors));
}
我尝试了很多可能的解决方案,但没有一个有效,总是返回对象的转义字符串表示。
任何帮助将不胜感激,我已经浪费了很多时间试图解决这个问题,我觉得这很愚蠢,但我无法继续前进,因为我什至无法完成我的第一个控制器
这里是git of the project,如果需要的话
【问题讨论】:
标签: json spring rest spring-boot