I have an api endpoint with request body like this.
{
"employeeId" : "1234",
"empName" : "John"
}
The fields are dynamic. So instead of creating a request class I am passing request body as HashMap<String, String> as below.
@PostMapping
public ResponseEntity<EmployeeResponse> getEmployees(@RequestBody HashMap<String, String> queryParams){
}
Now my requirement is to add something like this in the request body along with other dynamic fields.
{
"empAwardsReceived" : ["On the spot award", "Best employee award"]
}
How can we handle this? Can someone please help?
CodePudding user response:
You could try to use @RequestBody String queryParams
instead of @RequestBody HashMap<String, String> queryParams
.
Then you could try to look at eg. the Jackson library, which would help you to parse JSON as you want.
You probably could use code like presented below.
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.valueToTree(queryParams);
Then you could manipulate on JsonNode by using methods mentioned eg. in this article.
So adding a new JSON node should not be a problem.
CodePudding user response:
I changed RequestBody from HashMap<String, String> to HashMap<String, Object> and it worked.