【问题标题】:ResponseEntity producing escaped output instead of jsonResponseEntity 产生转义输出而不是 json
【发布时间】: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


    【解决方案1】:

    解决了。

    正如我所怀疑的,这是我的一个愚蠢的错误,

    ResponseEntity 将 String 作为 T,因此,当传递给响应时,String 由 StringHttpMessageConverter 处理,它对字符串进行转义。

    当使用 ResponseEntity 返回 Objects 作为 T 时,我们应该给一个要表示的对象或数据的包装类,或者转义字符串。

    另一种解决方法是关闭StringHttpMessageConverter,可以在WebMvcConfiguration中完成,但除非在某些情况下,否则不建议这样做。

    更多帮助请见:https://stackoverflow.com/a/37906098/12771022

    【讨论】:

      猜你喜欢
      • 2023-02-12
      • 2014-08-30
      • 2017-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多