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


问题内容

我想返回由两个字符串组成的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 » 20160810com.fasterxml.jackson.core我的pom.xml中,我仍然得到java.lang.IllegalArgumentException: No converter found for return value of type: class org.json.JSONObject为什么不杰克逊自动将我的JSON?这是一个标准的,只是简单的key:value。也许有更好的方法使用jackson.core中的某个类来创建简单的JSON,因此我不必在项目中包含Json
lib,而jackson会自动将其转换?


问题答案:

我不知道您为什么要使用两个JSON解析库。而不是创建一个JSONObject,而是创建Jackson的等效项ObjectNode

假设您可以访问ObjectMapperSpring 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自己序列化为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);