我不知道您为什么要使用两个JSON解析库。而不是创建一个JSONObject
,而是创建Jackson的等效项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
。以下某些解释来自我在这里的回答。
本质上,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
自己序列化为aString
并将其传递给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);