简体   繁体   中英

Handle two kinds of request body in controller - java

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?

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.

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

Below is the sample result.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM