@RequestBody helps your Spring Boot app read JSON data sent by a client and turn it into Java objects automatically.
@RequestBody for JSON input in Spring Boot
@PostMapping("/path")
public ResponseEntity<Type> methodName(@RequestBody Type variableName) {
// use variableName here
}The @RequestBody annotation tells Spring to convert JSON from the request body into the Java object.
The Java class used must have getters/setters or be a record for Spring to map JSON fields properly.
@PostMapping("/users") public ResponseEntity<User> addUser(@RequestBody User user) { // save user return ResponseEntity.ok(user); }
@PutMapping("/products/{id}") public ResponseEntity<Product> updateProduct(@PathVariable int id, @RequestBody Product product) { // update product with id return ResponseEntity.ok(product); }
This Spring Boot app has a POST endpoint at /users that accepts JSON like {"name":"Alice","age":30}.
Spring converts the JSON into a User record automatically using @RequestBody.
The endpoint returns the same user data as confirmation.
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } record User(String name, int age) {} @RestController class UserController { @PostMapping("/users") public ResponseEntity<User> addUser(@RequestBody User user) { // Just return the user received return ResponseEntity.ok(user); } }
Make sure your JSON keys match the Java object's field names exactly for mapping to work.
If JSON is invalid or missing required fields, Spring will return a 400 Bad Request error automatically.
Use records or classes with public getters/setters for smooth JSON to Java conversion.
@RequestBody reads JSON from HTTP requests and converts it to Java objects automatically.
It is useful for REST APIs that accept JSON input from clients.
Spring Boot handles errors if JSON is missing or malformed.