TExcelTAD
Home › Spring Boot › Request Bodies & JSON

Request Bodies & JSON

When a client creates or updates something, it sends the data as JSON in the request body. @RequestBody tells Spring to read that body and turn it into a Java object. The conversion — in both directions — is done by Jackson, the JSON library that spring-boot-starter-web includes and auto-configures.

Receiving JSON

java
public record NewTask(String title, String description, Priority priority, LocalDate dueDate) {}

public enum Priority { LOW, MEDIUM, HIGH }

@RestController
@RequestMapping("/api/tasks")
class TaskController {

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    Task create(@RequestBody NewTask body) {
        return service.create(body);
    }
}
bash · try it yourself
curl -s -X POST localhost:8080/api/tasks \
     -H "Content-Type: application/json" \
     -d '{"title":"Plan sprint","priority":"HIGH","dueDate":"2025-11-03"}'
{"id":4,"title":"Plan sprint","description":null,"priority":"HIGH","dueDate":"2025-11-03","done":false}

What happened:

  1. Content-Type: application/json selected Jackson's MappingJackson2HttpMessageConverter.
  2. Jackson matched JSON property names to the record components and called the canonical constructor. The missing description became null.
  3. "HIGH" became the enum constant and "2025-11-03" a LocalDate (Boot registers the Java-time module and writes dates as ISO strings, not arrays of numbers).
  4. The returned Task went through the same converter in reverse.

Common JSON errors

bash · try it yourself
curl -s -X POST localhost:8080/api/tasks -H "Content-Type: application/json" -d '{"title": "oops",}'
echo
curl -s -X POST localhost:8080/api/tasks -H "Content-Type: text/plain" -d 'hello' -w "%{http_code}\n"
{"timestamp":"2025-10-16T03:58:20.417+00:00","status":400,"error":"Bad Request","path":"/api/tasks"}
{"timestamp":"2025-10-16T03:58:20.466+00:00","status":415,"error":"Unsupported Media Type","path":"/api/tasks"}415
Problem Status
malformed JSON, wrong type ("priority":"SOON") 400 Bad Request
missing or wrong Content-Type 415 Unsupported Media Type
client only accepts XML (Accept: application/xml) 406 Not Acceptable

The exact reason (for example JSON parse error: Unexpected character ('}')) is logged as a warning on the server; the client gets a generic message so internals do not leak.

What Jackson does

Jackson reads JSON tokens and maps property names to constructor parameters or setters. This deliberately tiny parser handles a flat JSON object and builds a record the same way — matching keys by name and converting types:

java · try it yourself
import java.time.LocalDate;
import java.util.LinkedHashMap;
import java.util.Map;

enum Priority { LOW, MEDIUM, HIGH }

record NewTask(String title, String description, Priority priority, LocalDate dueDate) {}

class TinyJson {
    // parses {"key":"value", "key2":"value2"} with string values only
    static Map<String, String> parseFlat(String json) {
        Map<String, String> map = new LinkedHashMap<>();
        String body = json.strip();
        if (!body.startsWith("{") || !body.endsWith("}")) throw new IllegalArgumentException("not a JSON object");
        body = body.substring(1, body.length() - 1).strip();
        if (body.isEmpty()) return map;
        for (String pair : body.split(",")) {
            String[] kv = pair.split(":", 2);
            if (kv.length != 2) throw new IllegalArgumentException("JSON parse error near '" + pair.strip() + "'");
            map.put(unquote(kv[0]), unquote(kv[1]));
        }
        return map;
    }

    static String unquote(String s) {
        s = s.strip();
        if (s.equals("null")) return null;
        return s.substring(1, s.length() - 1);
    }

    static NewTask toNewTask(Map<String, String> m) {
        String p = m.get("priority");
        String d = m.get("dueDate");
        return new NewTask(m.get("title"), m.get("description"),
                p == null ? null : Priority.valueOf(p),
                d == null ? null : LocalDate.parse(d));
    }
}

class Main {
    public static void main(String[] args) {
        String json = "{\"title\":\"Plan sprint\",\"priority\":\"HIGH\",\"dueDate\":\"2025-11-03\"}";
        NewTask task = TinyJson.toNewTask(TinyJson.parseFlat(json));
        System.out.println(task);
        System.out.println("Due weekday: " + task.dueDate().getDayOfWeek());

        for (String bad : new String[] {"{\"title\":\"x\",\"priority\":\"SOON\"}", "{\"title\" \"x\"}"}) {
            try {
                TinyJson.toNewTask(TinyJson.parseFlat(bad));
            } catch (IllegalArgumentException e) {
                System.out.println("400 Bad Request: " + e.getMessage());
            }
        }
    }
}
NewTask[title=Plan sprint, description=null, priority=HIGH, dueDate=2025-11-03]
Due weekday: MONDAY
400 Bad Request: No enum constant Priority.SOON
400 Bad Request: JSON parse error near '"title" "x"'

Real Jackson is far more capable (nesting, arrays, numbers, escapes, streaming), but the contract is the same: names in JSON ↔ names in Java.

Customising the JSON

Annotations on the class change the mapping for that type:

java
@JsonInclude(JsonInclude.Include.NON_NULL)          // omit null fields
public record TaskView(
        long id,
        String title,
        @JsonProperty("is_done") boolean done,     // rename
        @JsonFormat(pattern = "dd.MM.yyyy") LocalDate dueDate,
        @JsonIgnore String internalNote) {}          // never serialised

Global settings go in application.properties:

properties
spring.jackson.default-property-inclusion=non_null
spring.jackson.property-naming-strategy=SNAKE_CASE
spring.jackson.deserialization.fail-on-unknown-properties=true

Note: Spring Boot's default is fail-on-unknown-properties=false: unknown JSON fields are silently ignored. That makes APIs tolerant of newer clients, but typos like "titel" go unnoticed. Turn it on if you prefer strictness.

Reading the raw body

Sometimes you need the body unparsed — for webhooks whose signature you must check, for example:

java
@PostMapping(path = "/webhooks/payment", consumes = "application/json")
ResponseEntity<Void> webhook(@RequestBody String rawJson,
                             @RequestHeader("X-Signature") String signature) {
    verifier.verify(rawJson, signature);
    ...
}

Test yourself

Which header must a client send so Spring uses Jackson to read a @RequestBody?

  1. Accept: application/json
  2. Content-Type: application/json
  3. X-Json: true
  4. No header is needed

With Spring Boot defaults, what happens to an unknown JSON property in the request?

  1. 400 Bad Request
  2. It is ignored
  3. 500 error
  4. It is stored in a map

How is a LocalDate serialised by default in Spring Boot?

  1. As a timestamp number
  2. As an array [2025,11,3]
  3. As an ISO string "2025-11-03"
  4. As toString() of the object