json - ResponseEntity 生成转义输出而不是 json

标签 json spring rest spring-boot

我对 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 中完成,但除非在某些情况下,否则不建议这样做。

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

关于json - ResponseEntity 生成转义输出而不是 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59885785/

相关文章:

java - Spring - 从 JSP GET 方法将值传递给 Controller

json - 如何在 Swagger UI 中禁用缓存

Spring - 如何在不存储在本地文件系统上的情况下将大型多部分文件上传到数据库

php - 输入框字段值不以json格式显示

spring - 升级到 Spring 3.0.3.RELEASE - 我在哪里可以找到 jar 的历史?

spring - 如何使用 OAuth2RestTemplate?

security - session 管理 : How to generate Authentication token for REST service ?( Jersey )

json - Wiremock:如何匹配不具有特定属性的 JSON 请求?

javascript - 将 PHP 中的 JSON 数据拆分为 JavaScript 中的三个数组

javascript - 启动时运行多个脚本的NodeJS包