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

后端 未结 2 2062
自闭症患者
自闭症患者 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:14

    Perhaps you are trying to send a request with JSON text in its body from a Postman client or something similar like this:

    {
     "userId": 3
    }
    

    This cannot be deserialized by Jackson since this is not an Integer (it seems to be, but it isn't). An Integer object from java.lang Integer is a little more complex.

    For your Postman request to work, simply put (without curly braces { }):

    3
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题