Skip to lesson

@RequestBody: reading JSON into objects

A staff member adds a new product by sending its details as JSON. The server must turn that text into a Java object before any code can use the name or the price.

@RequestBody turns the JSON body into a record

@RequestBody tells Spring to read the request body and turn the JSON into a Java object, usually a record, before your method runs. Turning text into an object is called deserialization.

A create request carries the new product as JSON. The example reads it into a record, so the method can use request.price() and not raw text.

Example 1 · CreateProductRequest.java and the create method

Runs in: the rest-lab practice project (Spring Boot 4.1)

CreateProductRequest.javaJava
package com.shoplite.lab.product;
import java.math.BigDecimal;
// POST body: stock and isActive may be left out (defaults 0 and true)public record CreateProductRequest(String sku, String name, Long categoryId, BigDecimal price,                                   Integer stock, Boolean isActive) {}
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)    // POST   /api/v1/products@ResponseStatus(HttpStatus.CREATED)public Product create(@RequestBody CreateProductRequest request) {    return productService.create(request);}
Sample output
$ curl -i -X POST http://localhost:8080/api/v1/products -H "Content-Type: application/json" -d '{"sku":"ACC-KB100","name":"Zebronics Wireless Keyboard","categoryId":4,"price":999.00,"stock":30}'
HTTP/1.1 201
Content-Type: application/json
Content-Length: 150
Date: Fri, 16 Oct 2026 05:07:37 GMT

{"id":16,"sku":"ACC-KB100","name":"Zebronics Wireless Keyboard","categoryId":4,"categoryName":"Accessories","price":999.00,"stock":30,"isActive":true}

What this code does

  • Jackson creates CreateProductRequest from the body: "categoryId":4 becomes a Long, "price":999.00 a BigDecimal with both decimals kept.
  • The body has no isActive, so request.isActive() is null and the service uses the contract default, true.
  • The method never sees JSON text; by the time it runs, the body is a typed record.

A record is the natural shape for a request body: its components list exactly the fields the client may send, and it cannot be changed after Jackson creates it. CreateProductRequest has the six fields of the ShopLite create-product body.

Only one parameter of a method can be the body, because a request has one body. Ids still come from the path and filters from the query string, as in the last lesson.

How JSON field names match record components

Deserialization is turning JSON text into a Java object. Jackson matches each JSON field to the record component with exactly the same name, case included; the order of the fields does not matter.

A client sends "name", "Name" or "product_name", and only one of them reaches name(). The examples show a misnamed field, and the strict setting that refuses it.

Example 2 · A misnamed field is silently ignored (default settings)

Runs in: the rest-lab practice project (Spring Boot 4.1)

Terminal
curl -i -X POST http://localhost:8080/api/v1/products -H "Content-Type: application/json" -d '{"sku":"ACC-MS200","productName":"Zebronics Wireless Mouse","categoryId":4,"price":499.00,"stock":15}'
Sample output
HTTP/1.1 201
Content-Type: application/json
Content-Length: 125
Date: Fri, 16 Oct 2026 05:07:37 GMT

{"id":17,"sku":"ACC-MS200","name":null,"categoryId":4,"categoryName":"Accessories","price":499.00,"stock":15,"isActive":true}

What this code does

  • The client wrote productName, but the record component is name. Jackson ignored the unknown field, so name is null.
  • The request still answered 201: the shop now has a product without a name, and nobody was told.
  • This run uses Spring Boot's default settings. Example 3 makes the same request fail loudly.

Example 3 · src/main/resources/application.properties: strict JSON

Runs in: the rest-lab practice project (Spring Boot 4.1)

Text
spring.application.name=rest-lab# ShopLite contract: an unknown field or a decimal sent for a whole number is a bad request (400)spring.jackson.deserialization.fail-on-unknown-properties=truespring.jackson.deserialization.accept-float-as-int=false# Then the same requests:# curl -i -X POST .../api/v1/products ... -d '{"sku":"ACC-MS200","productName":"Zebronics Wireless Mouse",...}'# curl -i -X POST .../api/v1/products ... -d '{"sku":"ACC-KB100",...,"stock":2.5}'
Sample output
HTTP/1.1 400
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 05:12:04 GMT
Connection: close

{"timestamp":"2026-10-16T05:12:04.776Z","status":400,"error":"Bad Request","path":"/api/v1/products"}
HTTP/1.1 400
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 05:12:05 GMT
Connection: close

{"timestamp":"2026-10-16T05:12:05.181Z","status":400,"error":"Bad Request","path":"/api/v1/products"}

Server log:
WARN ... Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Unrecognized property "productName" (class com.shoplite.lab.product.CreateProductRequest), not marked as ignorable]
WARN ... Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot coerce Floating-point value (2.5) to `java.lang.Integer` value (but could if coercion was enabled using `CoercionConfig`)]

What this code does

  • fail-on-unknown-properties=true makes an unknown field a 400, and the log names it: productName.
  • accept-float-as-int=false refuses "stock":2.5. Without it Jackson quietly stores 2, another silent bug.
  • Spring Boot reads any spring.jackson.deserialization.* setting from this file; restart the app after changing it. Every later example in this module runs with these two lines.

With Spring Boot's default settings, a field Jackson does not know is silently ignored. The component it was meant for stays null, and the request may even succeed with wrong data. That is the worst kind of bug: no error, just a product without a name.

The ShopLite contract says an unknown field is a bad request (400). One line in application.properties turns that on, and a second refuses a decimal such as 2.5 for a whole-number field, which Jackson would otherwise cut down to 2. Both lines belong in every ShopLite-style project.

Unknown fields, missing fields and null values

A wrapper type (Integer, Long, Boolean) is the object form of a primitive, so it can hold null. A missing or null JSON field arrives as null in a wrapper component; a primitive component refuses it.

A client leaves out stock, or sends "stock": null. The example shows what the record holds for a missing field, a null and a primitive int.

Example 4 · Missing fields, null values and a primitive int

Runs in: the rest-lab practice project (Spring Boot 4.1)

RestockController.javaJava
package com.shoplite.lab;
import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RestController;
@RestControllerpublic class RestockController {
    record RestockRequest(String sku, int quantity) { }   // int: a primitive
    @PostMapping("/lab/restock")    public String restock(@RequestBody RestockRequest request) {        return "Restock " + request.sku() + " by " + request.quantity();    }}
Sample output
{"id":18,"sku":"BK-ATOMIC","name":"Atomic Habits","categoryId":5,"categoryName":"Books","price":399.00,"stock":0,"isActive":true}
{"id":19,"sku":"BK-PRAG","name":"The Pragmatic Programmer","categoryId":5,"categoryName":"Books","price":650.00,"stock":0,"isActive":true}
HTTP/1.1 400
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 05:07:40 GMT
Connection: close

{"timestamp":"2026-10-16T05:07:40.507Z","status":400,"error":"Bad Request","path":"/lab/restock"}
HTTP/1.1 200
Content-Type: text/plain;charset=UTF-8
Content-Length: 22
Date: Fri, 16 Oct 2026 05:07:41 GMT

Restock BK-CLEAN by 20

Server log:
WARN ... Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot map `null` into type `int` (set `DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES` to 'false' to allow)]

What this code does

  • For the two products, a missing field and an explicit null give the same result: stock 0 and isActive true, because Integer and Boolean can hold null and the service supplies the defaults.
  • RestockRequest uses a primitive int quantity. Leaving it out gives 400 with Cannot map null into type int; sending it works.
  • Rule of thumb: wrapper types (Integer, Long, Boolean) for every request field, then let validation and the service decide what a null means.

The service decides what null means: in create, a missing stock becomes 0 and a missing isActive becomes true, as the contract says. A primitive component (int, long, boolean) cannot hold null. Jackson 3, which Spring Boot 4 uses, refuses the request with 400 and Cannot map null into type int. (Jackson 2 put a 0 there instead, so old code may behave differently.) Use wrapper types for anything the client may leave out.

Required fields that are missing are not refused here: "name" left out is simply null. Checking "name is required, 2 to 120 characters" is the job of the Validation module.

Malformed JSON and a missing body: 400

HttpMessageNotReadableException is thrown when Spring cannot turn the request body into the record: broken JSON, a value of the wrong type, an unknown field (strict setting) or no body at all. Spring Boot answers 400.

A client sends JSON with a comma after the last field. The server should answer with a clear 400 and not crash. The example sends broken JSON, no body and a wrong type.

Example 5 · Broken JSON, a missing body and a wrong type

Runs in: the rest-lab practice project (Spring Boot 4.1)

Terminal
curl -i -X POST http://localhost:8080/api/v1/products -H "Content-Type: application/json" -d '{"sku":"ACC-KB100","name":"Zebronics Wireless Keyboard",}'curl -i -X POST http://localhost:8080/api/v1/products -H "Content-Type: application/json"curl -i -X POST http://localhost:8080/api/v1/products -H "Content-Type: application/json" -d '{"sku":"ACC-KB100","name":"Zebronics Wireless Keyboard","categoryId":4,"price":"abc"}'curl -i -X POST http://localhost:8080/api/v1/products -H "Content-Type: application/json" -d "{'sku':'ACC-KB100'}"
Sample output
HTTP/1.1 400
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 05:07:41 GMT
Connection: close

{"timestamp":"2026-10-16T05:07:41.891Z","status":400,"error":"Bad Request","path":"/api/v1/products"}
HTTP/1.1 400
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 05:07:42 GMT
Connection: close

{"timestamp":"2026-10-16T05:07:42.622Z","status":400,"error":"Bad Request","path":"/api/v1/products"}
HTTP/1.1 400
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 05:07:43 GMT
Connection: close

{"timestamp":"2026-10-16T05:07:43.006Z","status":400,"error":"Bad Request","path":"/api/v1/products"}
HTTP/1.1 400
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 05:07:43 GMT
Connection: close

{"timestamp":"2026-10-16T05:07:43.452Z","status":400,"error":"Bad Request","path":"/api/v1/products"}

Server log:
WARN ... Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Unexpected character ('}' (code 125)): was expecting double-quote to start property name]
WARN ... Resolved [org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public com.shoplite.lab.product.Product com.shoplite.lab.product.ProductController.create(com.shoplite.lab.product.CreateProductRequest)]
WARN ... Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `java.math.BigDecimal` from String "abc": not a valid representation]
WARN ... Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Unexpected character (''' (code 39)): was expecting double-quote to start property name]

What this code does

  • All four requests fail with the same 400, and your method never runs. Only the log tells them apart.
  • Trailing comma: Jackson expected another "field" but found }. Single quotes: it found ' (code 39). JSON allows only double quotes.
  • No body: Required request body is missing names the method that needed it. "abc" for a BigDecimal is a wrong type. The Exception handling module returns these reasons to the client as malformed-request errors.

Typical broken JSON: a comma after the last field, single quotes instead of double quotes, a missing closing brace, or text where a number belongs ("price":"abc"). The log points at the exact problem: Unexpected character ('}' (code 125)): was expecting double-quote to start property name means a trailing comma.

A POST without -d sends no body, and the log says Required request body is missing. The response body says only "Bad Request", so learn to read the server log while you test.

Predict the output

Predict the status

The create method reads a JSON body into a record. What does each request get?

Round 1 of 3

The body is {"name":"Mouse","price":499,} with a comma after the last field.

@PostMapping
public ResponseEntity<ProductResponse> create(
@RequestBody CreateProductRequest request) {
...
}

Sending JSON bodies with curl on Windows and macOS

--data @file makes curl send the content of a file as the request body. For JSON it avoids every shell quoting problem, because the quotes are typed once in an editor.

A JSON body on the command line must reach curl with its double quotes intact, and shells quote differently. A file avoids the problem: save the JSON as product.json and send it with --data @product.json.

Example 6 · Windows PowerShell 5.1: three ways to send the same body

Runs in: the rest-lab practice project (Spring Boot 4.1)

Terminal
curl.exe -i -X POST http://localhost:8080/api/v1/products -H "Content-Type: application/json" -d '{"sku":"ACC-KB100","name":"Zebronics Wireless Keyboard","categoryId":4,"price":999.00,"stock":30}'curl.exe -X POST http://localhost:8080/api/v1/products -H "Content-Type: application/json" -d '{\"sku\":\"ACC-KB100\",\"name\":\"Zebronics Wireless Keyboard\",\"categoryId\":4,\"price\":999.00,\"stock\":30}'curl.exe -X POST http://localhost:8080/api/v1/products -H "Content-Type: application/json" --data "@product.json"
Sample output (Windows PowerShell 5.1)
PS> curl.exe -i -X POST http://localhost:8080/api/v1/products -H "Content-Type: application/json" -d '{"sku":"ACC-KB100",...}'
HTTP/1.1 400
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 05:09:27 GMT
Connection: close

{"timestamp":"2026-10-16T05:09:27.691Z","status":400,"error":"Bad Request","path":"/api/v1/products"}
PS> curl.exe -X POST http://localhost:8080/api/v1/products -H "Content-Type: application/json" -d '{\"sku\":\"ACC-KB100\",...}'
{"timestamp":"2026-10-16T05:09:27.826Z","status":400,"error":"Bad Request","path":"/api/v1/products"}
PS> curl.exe -X POST http://localhost:8080/api/v1/products -H "Content-Type: application/json" --data "@product.json"
{"id":16,"sku":"ACC-KB100","name":"Zebronics Wireless Keyboard","categoryId":4,"categoryName":"Accessories","price":999.00,"stock":30,"isActive":true}

Server log for the first two:
WARN ... JSON parse error: Unexpected character ('s' (code 115)): was expecting double-quote to start property name]
WARN ... JSON parse error: Unexpected end-of-input in VALUE_STRING]

What this code does

  • First command: PowerShell 5.1 stripped the inner double quotes, so the server received {sku:ACC-KB100,...}, and Jackson stopped at the s.
  • Second command: the \" escapes keep the quotes, but the space in "Zebronics Wireless Keyboard" splits the argument in two, so the JSON ends in the middle of a string.
  • Third command: product.json holds the same JSON, typed once in an editor. Nothing is lost on the way, so it works in every shell. The lesson verified this on PowerShell 5.1; in PowerShell 7.3+ the first form works too.

Windows PowerShell 5.1 removes the double quotes inside a single-quoted argument before curl.exe sees them, and escaping each quote as \" breaks as soon as a value contains a space. Use the file form there, or Command Prompt with the whole body in double quotes. Type curl.exe, because plain curl in PowerShell is a different command.

The macOS Terminal, Git Bash and PowerShell 7.3 or later keep the quotes, so the JSON can be wrapped in single quotes: -d '{"sku":"ACC-KB100","name":"Zebronics Wireless Keyboard"}'. A value that contains a single quote, such as Men's Shirt, needs the file form.

Next step

Check your understanding

12 quick questions