AI Hints
Home›Spring Boot Tutorial›What REST Is, Returning Objects as JSON and Records for Data
Spring Boot · Lesson 20 of 120

Returning Objects as JSON

From Java to JSON.

⏱ 2 min read▶ Video at 26:22🎓 Free
Watch this lesson in the Spring Boot courseWatch on YouTube ↗Full Spring Boot course

When a controller returns an object, Spring turns it into JSON. But which fields end up in the JSON? Let's find out.

  • Return an object
  • Spring makes JSON
  • Which fields?

A plain Book class

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; }
}

What Jackson sends

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
@RestController
public 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; }
}
Also uses _curl.sh
curl localhost:8080/book

Nested objects and lists

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
@RestController
public 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"));
    }
}
Output
{
  "title":"Dune",
  "author":{"name":"Frank Herbert","born":1920},
  "tags":["sci-fi","classic"]
}
Also uses _curl.sh
curl localhost:8080/book

Summary

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.

Key takeaways
  • Getters → fields
  • No getter, not sent
  • Nested JSON
Next up: Records for Data — short data classes