Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send Integer value in the form of JSON format and recieve in REST Controller?

I have one REST Controller where I have written this code

@PostMapping(value = "/otp")
public void otp(@RequestBody Integer mobile) {

    System.out.println(" Mobile = "+mobile);
}

And I am calling this method from Postman with the following inputs

URL : localhost:8080/otp

Body :

{
    "mobile":123456
}

But I am getting the following exception

org.springframework.http.converter.HttpMessageNotReadableException: 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

If I am taking String as a parameter like this

@PostMapping(value = "/otp")
public void otp(@RequestBody String mobile) {

    System.out.println(" Mobile = "+mobile);
}

And passing the inputs as

{
    "mobile":123456
}

Now it is printing in the console as follows

 Mobile = {
    "mobile":"123456"
}

But I want only this value 123456. How to achieve my requirement?

NOTE: I don't want to create any additional POJO class or even I don't want to send the data using query/path parameter.

like image 674
Altaf Ansari Avatar asked Jan 27 '23 03:01

Altaf Ansari


2 Answers

If you want to send your body like:

{
    "mobile":123456
}

You will create another object to receive the value.

But if you only want to accept the integer value without any other object, you will not put json object in request body, but only the integer itself.

Body:

12345

like image 103
Jaiwo99 Avatar answered Jan 31 '23 08:01

Jaiwo99


You can use a class as request body:

class Request {
    public Integer mobile;
}

and specify the parameter like this:

public void otp(@RequestBody Request mobile) {
...
like image 31
Henry Avatar answered Jan 31 '23 07:01

Henry