'Different payload/request body in post request
I have an endpoint:
/users
I have all CRUD operations but my question is how to handle different payloads for POST and delete request.
I mean I have userA which has fields like firstname,lastname, lifeStatus
And I have userB which has fields like name, lifeStatus, workStatus.
With some requestScope?
Solution 1:[1]
You question is not clear enough. You can accept the request body as JsonNode example :
@PostMapping("/test")
public void postTest(@RequestBody com.fasterxml.jackson.databind.JsonNode jsonNode)
{
System.out.println(jsonNode.get("name"));
}
the second method is to create a DTO wich contains all the possible attributes.
Example :
@PostMapping("/test")
public void postTest(@RequestBody UserDTO userDTO)
{
}
class UserDTO {
// put all possible attributes.
}
Solution 2:[2]
First, your DTO class must have all fields present (mandatory or non-mandatory) in the DTO class itself.
for example,
@JsonIgnoreProperties(ignoreUnknown=true)
public class UserDTO {
@JsonProperty("firstname")
private String firstName;
@JsonProperty("lastname")
private String lastName;
@JsonProperty("age")
private Integer age;
}
If UserA has only firstName and lastName fields then age will be null. Similarly, if UserB has only lastName and age then firstName will be null.
Alternatively, you can create two separate DTO classes for handling two different kinds of payloads.
Like this,
@PostMapping("/users")
public ResponseEntity postTest(@RequestBody UserDTOA dtoA) {
// code goes here
}
@DeleteMapping("/users")
public ResponseEntity deleteTest(@RequestBody UserDTOB dtoB) {
// code goes here
}
Solution 3:[3]
In this case you can use a Map<String, Object>
as request payload, or response
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Subham |
Solution 3 | Vinh Truong |