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?
CodePudding user response:
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.
}
CodePudding user response:
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
}
CodePudding user response:
In this case you can use a Map<String, Object>
as request payload, or response