Shubham Sahay
Shubham Sahay

Reputation: 88

how can i pass Json data in a Post method using spring boot? I want to pass few variables and use that variables in a different java class

I am very new to Spring Boot and trying out different things.

I have a class in which a method does simple calculation, accepts two numbers and give addition.Now i want to pass the numbers through api in json format and return the addition of the number.

Can we pass the variables in a @POSTMapping and return the result ?

Controller class

    @RestController
    @RequestMapping(value="/TC")
    public class CountSpringAppController {

    @Autowired
    private CountService countService;


    @PostMapping(value="/add/{number1}/{number2}") 
    public int getCount(@PathVariable int num1,@PathVariable int num2) {

        return countService.count(num1, num2);

    }`

service class

 @Service
        public class CountService {

    public int count(int num1, int num2) {
        return num1+num2;
    }

}

input

{
"num1":1,
"num2":1
}

output

2

Upvotes: 0

Views: 6100

Answers (2)

Akash Shah
Akash Shah

Reputation: 616

Make a Num class which will accept json

 Class Num{
        int num1;
        int num2;
        //getter setter
    }

now use that class for getting data from json body

  @RequestMapping(value="/add",method = RequestMethod.POST, consumes="application/json", produces = "application/json")
    public int getCount(@RequestBody Num request) {

        return countService.count(request.getNum1(),request.getNum2());

    }`

Upvotes: 5

Alan Hay
Alan Hay

Reputation: 23246

You can do as below. This prevents the need for an additional data class:

@PostMapping(value="/add") 
public int getCount(@RequestBody Map<String, Integer> data) {

    return countService.count(data.get("number1"), data.get("number2"));

}

Upvotes: 1

Related Questions