How to Get List of Objects via Requestbody in Spring
There are three ways to receive list or array of objects via @RequestBody annotation.
1. Use List with @RequestBody
Suppose we have an entity class named UserCreateForm
, it is used to hold user information which is necessary for creating a new user.
//form class for creating user
@Data
@NoArgsConstructor
@AllArgsConstructor
public class UserCreateForm {
private String name;
private Integer age;
}
// controller method
@PostMapping("/users")
public void batchCreateUser(@RequestBody List<UserCreateForm> forms) {
log.info("request: {}", forms);
}
If you call api with below data:
POST http://localhost:8080/list-via-request-body/users/1
Content-Type: application/json
[
{
"name": "Jone",
"age": 21
},
{
"name": "Jessica",
"age": 20
}
]
the output should be:
user: UserCreateForm(name=Jone, age=21)
user: UserCreateForm(name=Jessica, age=20)
2. Use array with @RequestBody
@PostMapping(value = "/users")
public @ResponseBody List<User> batchCreate(@RequestBody UserCreateForm[] forms) {
log.info("array of users: {}", forms);
return userService.create(forms);
}
THe input and output shoule be the same with the situation when you are using List
.
3. Use a wrapper class
When you are working on an older version of spring or spring boot, the previous ways might not work at all, in that case a quick workaround is to have a wrapper class.
// User class
@Data
@NoArgsConstructor
@AllArgsConstructor
public class UserCreateForm {
private String name;
private Integer age;
}
// Wrapper class for User
@Data
@NoArgsConstructor
@AllArgsConstructor
public class UserWrapperForm {
List<UserCreateForm> users;
}
// Controller class
@PostMapping(value = "/users")
public @ResponseBody List<User> batchCreate(@RequestBody UserWrapperForm form) {
return userService.create(form);
}
the request turned out to be this:
POST http://localhost:8080/list-via-request-body/users/3
Content-Type: application/json
{
"users": [
{
"name": "Jone",
"age": 21
},
{
"name": "Jessica",
"age": 20
}
]
}