我不知道你为什么使用两个 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);