createUser(@RequestBody -6ren">
gpt4 book ai didi

java - 为什么 Spring MVC 报告 "No converter found for return value of type: class org.json.JSONObject"?

转载 作者:行者123 更新时间:2023-11-29 04:35:00 25 4
gpt4 key购买 nike

我想返回一个由两个字符串组成的 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);
}

我的 pom.xml 中有 Json » 20160810com.fasterxml.jackson.core 并且我仍然有 java.lang。 IllegalArgumentException:找不到类型为 class org.json.JSONObject 的返回值的转换器 为什么 Jackson 不自动转换我的 JSON?这是一个标准的,只是简单的键:值。也许有更好的方法可以使用 jackson.core 中的某个类创建简单的 JSON,这样我就不必在我的项目中包含 Json 库,jackson 会自动转换它们?

最佳答案

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

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

@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。以下部分解释来 self 的回答here .

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

此实现只是循环遍历 HttpMessageConverter 的集合实例,检查实例是否可以序列化 ResponseEntitybody,如果可以则使用它。

不幸的是,Jackson 的HttpMessageConverter 实现,MappingJackson2HttpMessageConverter ,使用 ObjectMapper 序列化这些对象,而 ObjectMapper 无法序列化 JSONObject 因为它无法发现类中的任何属性(即 bean getters ).

Jackson 的 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);

关于java - 为什么 Spring MVC 报告 "No converter found for return value of type: class org.json.JSONObject"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42027491/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com