我对 Spring 框架相当陌生,我正在尝试通过开发示例项目来学习
也许这是一个愚蠢的问题,但我根本找不到任何帮助。
当验证规则未通过时,我的 Controller 使用转义字符串而不是对象的 json 表示来响应请求。我使用 bean 验证器和 Gson 生成错误的错误 json 表示。
我的 Controller 响应:
"{\"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"}
这是我的 Controller :
@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));
}
我尝试了很多可能的解决方案,但它们都不起作用,总是返回对象的转义字符串表示形式。
任何帮助将不胜感激,我花了很多时间试图解决这个问题,我觉得这很愚蠢,但我无法继续前进,因为我什至无法完成我的第一个 Controller
这是git of the project ,如果需要的话
最佳答案
已解决。
正如我所怀疑的,这是我的一个愚蠢的错误,
ResponseEntity 将 String 视为 T,因此,当传递给响应时,String 由 StringHttpMessageConverter 处理,从而对字符串进行转义。
当使用 ResponseEntity 将对象作为 T 返回时,我们应该给出一个要表示的对象或数据的包装类,或者转义字符串。
另一个解决方法是关闭 StringHttpMessageConverter,这可以在 WebMvcConfiguration 中完成,但除非在某些情况下,否则不建议这样做。
关于json - ResponseEntity 生成转义输出而不是 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59885785/