Home > other >  Handle two kinds of request body in controller - java
Handle two kinds of request body in controller - java

Time:11-24

I have a request body like this for post method.

{
"emp_id" : "1234"
}

Controller is like this.

@PostMapping("/employees)
public ResponseEntity<EmployeeResponse> getMatchingValues(@RequestBody HashMap<String,String> params){
}

Now my request body will be updated to the one as shown below.

{
"emp_id" : "1234",
"ids" : ["4567","9087"]
}

How can I update the post mapping in controller? Can someone help on this?

CodePudding user response:

You can consume the params in Map<String, Object>

Below is the sample result.

@PostMapping("/employees)
public ResponseEntity<EmployeeResponse> getMatchingValues(@RequestBody HashMap<String,String> params){
            System.out.println("params = " params);
  
}

Output is : params = {emp_id=1234, ids=[4567, 9087]}

CodePudding user response:

It will be easier to handle if you use a POJO to get the values from the request body

public RequestData{
  private String emp_id;
  private List<String> ids;
...
//TODO: getters and setters here
}

And then in the controller:

@PostMapping("/employees)
public ResponseEntity<EmployeeResponse> getMatchingValues(@RequestBody RequestData requestData){
}

This way, if a field is not included in the request, it will map it to null.

  • Related