Afsrd3
Afsrd3

Reputation: 127

Get integer on requestbody

Ineed to get the id to delete on the database but I cant get the id parameter this way

@RequestMapping(value = {"/delete/search/","/delete/search"}, method = RequestMethod.DELETE)
    @ResponseBody
    public Integer deleteUser(@RequestBody Integer id_search) {
        return id_search;
    }

I get this error message

"message": "JSON parse error: Can not deserialize instance of java.lang.Integer out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.Integer out of START_OBJECT token\n at [Source: java.io.PushbackInputStream@1b77938; line: 1, column

Upvotes: 9

Views: 17278

Answers (2)

Javier Sanchez C
Javier Sanchez C

Reputation: 251

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

{
 "id_search":2
}

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 { }):

2

Upvotes: 9

pvpkiran
pvpkiran

Reputation: 27068

This statement is wrong

@RequestBody Integer id_search

This means Spring is expecting a body of type Integer class. But what you are passing as the body doesn't match Integer class.

You have many options to fix this.

  1. Remove @RequestBody and just declare as

    public Integer deleteUser(Integer id_search) {...}
    

    With this you need to call this endpoint as

    http://localhost:8080/seviceRS/delete/search?id_search=2
    
  2. You can pass it as PathVariable like this

    http://localhost:8080/seviceRS/delete/search/2
    

    For this to work change your controller method like this

    @RequestMapping(value = 
    {"/delete/search/{id_search}"}, method = 
                                           RequestMethod.DELETE)
      @ResponseBody
      public Integer deleteUser(Integer id_search) {...}
    
  3. If you want to send as body, then you should create a class which matches the json that you are sending.

    For example. Create a class like

     class Demo {
      private int id_search;
      //Getters & Setters
     }
    

    With this approach your controller method looks like

    @RequestMapping(value = {"/delete/search/}, method = 
                      RequestMethod.DELETE)
    @ResponseBody
    public Integer deleteUser(Demo demo) {
         demo.getId_Search();
    }
    

Upvotes: 8

Related Questions