Bird
Raised Fist0
Spring Bootframework~10 mins

@RequestBody for JSON input in Spring Boot - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - @RequestBody for JSON input
Client sends HTTP POST with JSON body
↓
Spring Boot Controller receives request
↓
@RequestBody annotation tells Spring to parse JSON
↓
Spring converts JSON to Java object
↓
Controller method uses Java object
↓
Controller returns response
This flow shows how Spring Boot uses @RequestBody to convert incoming JSON into a Java object for the controller to use.
Execution Sample
Spring Boot
record User(String name, int age) {}

@PostMapping("/users")
public String addUser(@RequestBody User user) {
    return "User " + user.name() + " added";
}
This code receives JSON with name and age, converts it to a User object, and returns a confirmation string.
Execution Table
StepActionInput/ConditionResultNotes
1Receive HTTP POSTBody: {"name":"Alice","age":30}Request receivedClient sends JSON data
2Spring reads @RequestBodyAnnotation presentTriggers JSON parsingSpring knows to parse body as JSON
3Parse JSON{"name":"Alice","age":30}Create User(name="Alice", age=30)JSON converted to Java record
4Call addUser methodUser object with name=Alice, age=30Method executesUser object passed as parameter
5Return responseString "User Alice added"Response sent to clientConfirmation message returned
6EndNo more stepsRequest completeProcess finished
💡 Request handled fully; JSON parsed and method executed
Variable Tracker
VariableStartAfter Step 3After Step 4Final
usernullUser(name="Alice", age=30)User(name="Alice", age=30)User(name="Alice", age=30)
Key Moments - 3 Insights
Why does Spring need the @RequestBody annotation?
Because @RequestBody tells Spring to convert the incoming JSON into a Java object. Without it, Spring treats the body as plain text or ignores it. See execution_table step 2.
What happens if the JSON keys don't match the Java object's fields?
Spring will fail to map those fields correctly, possibly throwing an error or setting fields to default values. This is because JSON keys must match Java property names for conversion (step 3).
Can the controller method use the Java object directly after @RequestBody?
Yes, after Spring converts JSON to the Java object, the method receives it ready to use, as shown in step 4.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'user' after step 3?
AJSON string
Bnull
CUser(name="Alice", age=30)
DEmpty object
💡 Hint
Check variable_tracker after Step 3 for 'user' value.
At which step does Spring convert JSON into a Java object?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Look at execution_table action describing JSON parsing.
If the @RequestBody annotation is removed, what changes in the execution?
ASpring treats the body as plain text, no conversion
BSpring still converts JSON automatically
CThe method receives a Java object anyway
DThe server throws an error immediately
💡 Hint
Refer to key_moments about the role of @RequestBody (step 2).
Concept Snapshot
@RequestBody annotation in Spring Boot
- Used on controller method parameters
- Converts incoming JSON request body into Java object
- Requires matching JSON keys and Java fields
- Enables easy use of JSON data in Java methods
- Without it, body is not parsed as JSON
Full Transcript
This visual execution shows how Spring Boot uses the @RequestBody annotation to handle JSON input. When a client sends a POST request with JSON data, Spring sees the @RequestBody annotation on the controller method parameter. This tells Spring to parse the JSON body and convert it into a Java object matching the parameter type. The example uses a User record with name and age fields. The JSON keys must match these fields for correct mapping. After conversion, the controller method receives the User object and can use it directly. The method then returns a confirmation string. If @RequestBody is missing, Spring does not parse the JSON and treats the body as plain text. This flow helps beginners understand how JSON input is handled step-by-step in Spring Boot controllers.

Practice

(1/5)
1. What is the main purpose of the @RequestBody annotation in a Spring Boot controller?
easy
A. To validate form data submitted via GET requests
B. To send JSON data back in the HTTP response
C. To map URL query parameters to method arguments
D. To automatically convert JSON from the HTTP request body into a Java object

Solution

  1. Step 1: Understand the role of @RequestBody

    @RequestBody tells Spring Boot to take JSON data sent in the HTTP request body and convert it into a Java object automatically.
  2. Step 2: Differentiate from other annotations

    It does not handle response data (that's @ResponseBody), nor does it map query parameters or validate GET form data.
  3. Final Answer:

    To automatically convert JSON from the HTTP request body into a Java object -> Option D
  4. Quick Check:

    @RequestBody = JSON to Java object [OK]
Hint: Remember: @RequestBody reads JSON input from request body [OK]
Common Mistakes:
  • Confusing @RequestBody with @ResponseBody
  • Thinking it maps URL parameters
  • Assuming it validates data automatically
2. Which of the following method signatures correctly uses @RequestBody to accept a JSON object representing a User in a Spring Boot controller?
easy
A. public ResponseEntity<String> addUser(@RequestBody User user)
B. public ResponseEntity<String> addUser(@RequestParam User user)
C. public ResponseEntity<String> addUser(@PathVariable User user)
D. public ResponseEntity<String> addUser(User user)

Solution

  1. Step 1: Identify correct annotation for JSON body

    @RequestBody is required to tell Spring Boot to convert JSON in the request body to a User object.
  2. Step 2: Check other annotations

    @RequestParam reads query parameters, @PathVariable reads URL path segments, and no annotation means no automatic JSON conversion.
  3. Final Answer:

    public ResponseEntity<String> addUser(@RequestBody User user) -> Option A
  4. Quick Check:

    JSON input needs @RequestBody [OK]
Hint: Use @RequestBody for JSON input, not @RequestParam or @PathVariable [OK]
Common Mistakes:
  • Using @RequestParam instead of @RequestBody
  • Forgetting @RequestBody annotation
  • Confusing @PathVariable with JSON input
3. Given the following controller method:
  @PostMapping("/add")
  public String addUser(@RequestBody User user) {
    return "Hello " + user.getName();
  }

And the JSON sent in the request body is:
{"name": "Alice"}

What will be the response?
medium
A. HTTP 400 Bad Request
B. "Hello null"
C. "Hello Alice"
D. Compilation error

Solution

  1. Step 1: Understand JSON to Java object mapping

    The JSON {"name": "Alice"} maps to a User object with name set to "Alice".
  2. Step 2: Check method return value

    The method returns "Hello " + user.getName(), so it returns "Hello Alice".
  3. Final Answer:

    "Hello Alice" -> Option C
  4. Quick Check:

    JSON name maps to user.getName() = "Hello Alice" [OK]
Hint: JSON keys map to object fields, so output uses those values [OK]
Common Mistakes:
  • Assuming user.getName() is null
  • Expecting HTTP error without malformed JSON
  • Confusing request body with query parameters
4. Consider this controller method:
@PostMapping("/user")
public String createUser(@RequestBody User user) {
  return user.getEmail();
}

If the client sends an empty request body, what will happen?
medium
A. Spring Boot throws an HTTP 400 Bad Request error
B. The method returns null
C. The method returns an empty string
D. Compilation error due to missing @RequestBody

Solution

  1. Step 1: Check behavior with empty JSON body

    When @RequestBody expects JSON but receives empty body, Spring Boot cannot create the User object.
  2. Step 2: Understand Spring Boot error handling

    Spring Boot responds with HTTP 400 Bad Request for missing or malformed JSON input.
  3. Final Answer:

    Spring Boot throws an HTTP 400 Bad Request error -> Option A
  4. Quick Check:

    Empty JSON body causes HTTP 400 error [OK]
Hint: Empty JSON body with @RequestBody causes HTTP 400 error [OK]
Common Mistakes:
  • Assuming method returns null or empty string
  • Thinking compilation error occurs
  • Ignoring HTTP error on missing JSON
5. You want to create a Spring Boot REST endpoint that accepts a JSON array of User objects in the request body and returns the count of users received. Which method signature correctly uses @RequestBody to achieve this?
hard
A. public int countUsers(@RequestBody User user)
B. public int countUsers(@RequestBody List<User> users)
C. public int countUsers(@RequestParam List<User> users)
D. public int countUsers(@PathVariable List<User> users)

Solution

  1. Step 1: Identify correct parameter type for JSON array

    To accept a JSON array of User objects, the method parameter should be a List<User> annotated with @RequestBody.
  2. Step 2: Exclude incorrect annotations and types

    @RequestParam and @PathVariable do not handle JSON body. Single User parameter cannot accept an array.
  3. Final Answer:

    public int countUsers(@RequestBody List<User> users) -> Option B
  4. Quick Check:

    JSON array maps to List<User> with @RequestBody [OK]
Hint: Use List<User> with @RequestBody for JSON arrays [OK]
Common Mistakes:
  • Using single User instead of List<User>
  • Using @RequestParam or @PathVariable for JSON body
  • Forgetting @RequestBody annotation
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard