为什么 Spring MVC 报告“找不到类型的返回值的转换器:class org.json.JSONObject”?

2023-12-12

我想返回一个由两个字符串组成的 JSON,但不知道如何实现它。这是我的代码:

 @PostMapping
public ResponseEntity<> createUser(@RequestBody User user ) {

    JSONObject responseJson = new JSONObject();

    if (userService.userExists(user)) {

        responseJson.put("status", "User with that username already exists.");

        return new ResponseEntity<>(responseJson, HttpStatus.BAD_REQUEST);
    }

    responseJson.put("status", "User created.");

    return new ResponseEntity<>(responseJson, HttpStatus.CREATED);
}

我有Json » 20160810 and com.fasterxml.jackson.core在我的 pom.xml 中,我仍然得到java.lang.IllegalArgumentException: No converter found for return value of type: class org.json.JSONObject为什么 Jackson 不自动转换我的 JSON?这是一个标准的,只是简单的键:值。也许有更好的方法来使用 jackson.core 中的某些类创建简单的 JSON,这样我就不必在我的项目中包含 Json lib 并且 jackson 会自动转换它们?


我不知道你为什么使用两个 JSON 解析库。而不是创建一个JSONObject,创建杰克逊的等价物ObjectNode.

假设您有权访问ObjectMapper由您的 Spring MVC 堆栈使用

@Autowired
private ObjectMapper objectMapper;

用它来创建和填充ObjectNode

ObjectNode jsonObject = mapper.createObjectNode();
jsonObject.put("status", "User with that username already exists.");
// don't forget to change return type to support this
return new ResponseEntity<>(jsonObject, HttpStatus.BAD_REQUEST);

由于这是 Jackson 类型,Jackson 知道如何将其序列化。

它不知道如何序列化JSONObject。以下部分解释来自我的回答here.

本质上,Spring MVC 使用HandlerMethodReturnValueHandler处理返回值的实现@RequestMapping (@PostMapping) 带注释的方法。为了ResponseEntity,该实现是HttpEntityMethodProcessor.

这个实现只是循环遍历一个集合HttpMessageConverter实例,检查实例是否可以序列化body of the ResponseEntity,并在可以的情况下使用它。

不幸的是,杰克逊的HttpMessageConverter执行,MappingJackson2HttpMessageConverter,使用ObjectMapper序列化这些对象并ObjectMapper无法序列化JSONObject因为它无法发现类中的任何属性(即 bean getters)。

杰克逊的HttpMessageConverter不能这样做,默认注册的所有其他也不能这样做。这就是 Spring MVC 报告“没有转换器”的原因。

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalArgumentException: No converter found for return value of type: class org.json.JSONObject

另一种解决方案是序列化JSONObject自己对一个String并将其传递给ResponseEntity。显然您需要更改返回类型以支持String。在这种情况下,Spring MVC 将使用StringHttpMessageConverter。但是,您需要指定application/json自己输入内容类型,因为它不会添加它。例如,

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
return new ResponseEntity<>(responseJson.toString(), headers, HttpStatus.BAD_REQUEST);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么 Spring MVC 报告“找不到类型的返回值的转换器:class org.json.JSONObject”? 的相关文章

随机推荐