Records as JSON
A record as JSON is a Java record turned into JSON text. Each part of the record becomes a field in the JSON.
The task record
This record has two parts. The JSON will carry both names.
record TaskForm(String title, boolean done) {}Return one task as JSON
Ask for /task. The answer is the record as JSON.
@GetMapping("/task")
public TaskForm task() {
return new TaskForm("Buy milk", false);
}Example
package com.example.demo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TaskController {
record TaskForm(String title, boolean done) {
}
@GetMapping("/task")
public TaskForm task() {
return new TaskForm("Buy milk", false);
}
}Key points
- A record holds data in named parts, like title and done.
- Spring Boot turns a record into JSON when a route returns it.
- Each record part becomes a JSON field with the same name.
- The fields appear in the order the record lists them.
- A boolean part becomes true or false in the JSON.
In this example, the record TaskForm holds a title and a done flag. The controller has one route. The route answers GET requests for /task. The method builds one task with the title Buy milk and done set to false. Spring Boot turns the record into JSON for the answer. The JSON carries title first and done second, in record order.
Note
The JSON carries no Java type names, only field names and values.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What JSON does new TaskForm("Buy milk", false) become?