我不知道您为什么要使用两个JSON解析库。而不是创建一个
JSONObject,而是创建Jackson的等效项
ObjectNode。
假设您可以访问
ObjectMapperSpring MVC堆栈使用的
@Autowiredprivate 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 thisreturn new ResponseEntity<>(jsonObject, HttpStatus.BAD_REQUEST);由于这是Jackson类型,Jackson知道如何序列化它。
它不知道如何序列化
JSONObject。以下某些解释来自我在这里的回答。
本质上,Spring
MVC使用
HandlerMethodReturnValueHandler实现来处理
@RequestMapping(
@PostMapping)带注释的方法返回的值。对于
ResponseEntity,实现是
HttpEntityMethodProcessor。
此实现仅循环遍历
HttpMessageConverter实例集合,检查实例是否可以序列化,并
body在可以的情况下
ResponseEntity使用它。
不幸的是,Jackson的
HttpMessageConverter实现
MappingJackson2HttpMessageConverter使用
ObjectMapper来序列化这些对象,
ObjectMapper并且无法序列化,
JSONObject因为它无法发现类中的任何属性(即bean
getter)。
杰克逊
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自己序列化为a
String并将其传递给
ResponseEntity。显然,您需要将返回类型更改为support
String。在这种情况下,Spring
MVC将使用
StringHttpMessageConverter。但是,您需要自己指定
application/json内容类型,因为它不会添加内容类型。例如,
HttpHeaders headers = new HttpHeaders();headers.setContentType(MediaType.APPLICATION_JSON);return new ResponseEntity<>(responseJson.toString(), headers, HttpStatus.BAD_REQUEST);



