Why does Spring MVC report “No converter found for return value of type: class org.json.JSONObject”?

后端 未结 2 561
猫巷女王i
猫巷女王i 2021-01-27 03:45

I want to return a JSON made of two strings and don\'t know how to implement it. Here is my code:

 @PostMapping
public ResponseEntity<> createUser(@Request         


        
2条回答
  •  旧巷少年郎
    2021-01-27 04:46

    Jackson does not know about org.json.JSONObject, use JsonNode instead for key/value pair.

    Update after comment:

    Could you write me an example how would you use it? I find it a bit confusing

    @PostMapping
    public ResponseEntity createUser(@RequestBody User user) {
            ObjectMapper objectMapper = new ObjectMapper();
    
            Map responseJson = new HashMap<>();
            if (userService.userExists(user)) {
                responseJson.put("status",
                        "User with that username already exists.");
                JsonNode jsonNode = objectMapper.valueToTree(responseJson);
                return new ResponseEntity(jsonNode,
                        HttpStatus.BAD_REQUEST);
            }
            responseJson.put("status", "User created.");
            JsonNode jsonNode = objectMapper.valueToTree(responseJson);
            return new ResponseEntity<>(jsonNode, HttpStatus.CREATED);
    }
    

提交回复
热议问题