JsonMappingException: Can not deserialize instance of java.lang.Integer out of START_OBJECT token

后端 未结 2 2075
自闭症患者
自闭症患者 2021-01-04 00:03

I wanted to write a small and simple REST service using Spring Boot. Here is the REST service code:

@Async
@RequestMapping(value = \"/getuser\", method = POS         


        
2条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-04 00:27

    Obviously Jackson can not deserialize the passed JSON into an Integer. If you insist to send a JSON representation of a User through the request body, you should encapsulate the userId in another bean like the following:

    public class User {
        private Integer userId;
        // getters and setters
    }
    

    Then use that bean as your handler method argument:

    @RequestMapping(...)
    public @ResponseBody Record getRecord(@RequestBody User user) { ... }
    

    If you don't like the overhead of creating another bean, you could pass the userId as part of Path Variable, e.g. /getuser/15. In order to do that:

    @RequestMapping(value = "/getuser/{userId}", method = POST, produces = "application/json")
    public @ResponseBody Record getRecord(@PathVariable Integer userId) { ... }
    

    Since you no longer send a JSON in the request body, you should remove that consumes attribute.

提交回复
热议问题