Book has three private fields, title, price, and secret. The constructor sets title, and price. And there are two getters, get title, and get price. Notice that secret has no getter.
Book.javajava
public class Book { private final String title; private final double price; private final String secret = "staff only"; public Book(String title, double price) { this.title = title; this.price = price; } public String getTitle() { return title; } public double getPrice() { return price; }}
The controller returns a new book. Jackson, the JSON library, calls every getter to build the JSON. Get title becomes title, and get price becomes price. Run it. We get title, and price. Secret is missing, because it has no getter.
BookController.javajava
@RestControllerpublic class BookController { @GetMapping("/book") public Book book() { return new Book("Dune", 9.99); }}
Output
{"title":"Dune","price":9.99}
Also uses Book.java
public class Book { private final String title; private final double price; private final String secret = "staff only"; public Book(String title, double price) { this.title = title; this.price = price; } public String getTitle() { return title; } public double getPrice() { return price; }}
Objects can hold other objects, and lists. Book holds an author, and a list of tags. Run it. The author becomes a JSON object inside the book. And the tags become a JSON list.
BookController.javajava
@RestControllerpublic class BookController { record Author(String name, int born) {} record Book(String title, Author author, List<String> tags) {} @GetMapping("/book") public Book book() { Author frank = new Author("Frank Herbert", 1920); return new Book("Dune", frank, List.of("sci-fi", "classic")); }}
Jackson turns objects into JSON, using their getters. Nested objects become nested JSON, and lists become JSON lists. Next, records, the easiest way to hold data.