Request and Response Bodies with JSON

Site Admin · 11 Sep 2026 · 5 views

Request and Response Bodies with JSON

Modern web APIs exchange JSON. Spring Boot handles the conversion for you: Jackson serializes your response objects to JSON and deserializes incoming JSON into your request objects. Your job is to define clean data shapes and let the framework do the wire work.

Binding a request body

Annotate a method parameter with @RequestBody and Spring converts the incoming JSON to the parameter type. Combine it with @PostMapping to create resources. Field names in JSON map to Java field names, and Jackson handles nested objects and lists.

public record ProductRequest(String name, double price, int stock) {}

@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public Product create(@RequestBody ProductRequest request) {
    return service.create(request);
}

Representing the response

Return a class, a record, or a ResponseEntity, and Spring writes it as JSON with a default status of 200. Set a specific status with @ResponseStatus or by returning ResponseEntity.status(...).body(...). Records are a great fit for request and response DTOs because they are immutable and come with equals, toString, and accessors for free.

Configuring the conversion

Jackson ignores unknown JSON properties by default in Boot, which lets your API evolve without breaking old clients. You can exclude null fields, rename fields with @JsonProperty, and format dates via spring.jackson.* properties.

Testing with curl

curl -X POST http://localhost:8080/api/products
  -H "Content-Type: application/json"
  -d '{"name":"Keyboard","price":49.9,"stock":12}'

Keep DTOs separate

Do not expose entity objects directly in every endpoint. Entities carry lazy associations and persistence concerns that Jackson can trip over, producing circular references or serializing more than you intend. A small DTO or record per request and response keeps your API stable and your mapping explicit.

Key Points

  • @RequestBody deserializes JSON into typed parameters.
  • Return DTOs, records, or ResponseEntity and Spring serializes them to JSON.
  • Records make concise, immutable request and response models.
  • Use @ResponseStatus or ResponseEntity to control HTTP status.
  • Prefer DTOs over raw entities at API boundaries.
Share this post:

Comments (0)

Please login or register to comment.