AI Hints
Home›Spring Boot Tutorial›HTTP Methods, Status Codes and JSON
Spring Boot · Lesson 12 of 120

JSON

The language of APIs.

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

When a server sends data to an app, it usually uses JSON. It's simple text, that both people and programs can read.

  • Data as text
  • Easy to read
  • Used by almost every API

A JSON object

Curly braces hold an object, a set of named values. Each name is in double quotes, followed by a colon, and the value. Values can be text, numbers, or true and false. Square brackets hold a list. And commas separate the items.

book.jsonjson
{
  "title": "Dune",
  "author": "Frank Herbert",
  "price": 9.99,
  "inStock": true,
  "tags": ["sci-fi", "classic"]
}

Java and JSON

A Java object, and a JSON object, map neatly onto each other. Fields become names. Strings become text in quotes. Numbers and booleans stay the same. And a Java list becomes a JSON list.

Java

  • record Book(title, price)"Dune", 9.99List<Book>

JSON

  • {"title": ..., "price": ...}"Dune", 9.99[ {...}, {...} ]

Objects become JSON

Here, Book is a record, a short way to write a data class. We'll look at records closely, in lesson twenty one. The first endpoint returns one book. The second returns a list of books. Spring turns them into JSON for us, using a library called Jackson. Run it. One book becomes a JSON object, and the list becomes a JSON list, with two objects.

BookController.javajava
@RestController
public class BookController {

    record Book(String title, String author, double price, boolean inStock) {}

    @GetMapping("/book")
    public Book book() {
        return new Book("Dune", "Frank Herbert", 9.99, true);
    }

    @GetMapping("/books")
    public List<Book> books() {
        return List.of(new Book("Dune", "Frank Herbert", 9.99, true),
                       new Book("Circe", "Madeline Miller", 10.99, false));
    }
}
Output
$ curl localhost:8080/book
{"title":"Dune","author":"Frank Herbert","price":9.99,"inStock":true}
$ curl localhost:8080/books
[
  {"title":"Dune","author":"Frank Herbert","price":9.99,"inStock":true},
  {"title":"Circe","author":"Madeline Miller","price":10.99,"inStock":false}
]
Also uses _curl.sh
curl localhost:8080/book
curl localhost:8080/books

Summary

JSON uses curly braces for objects, and square brackets for lists. Spring converts your Java objects to JSON automatically. Next, testing with curl.

Key takeaways
  • { } objects
  • [ ] lists
  • Java → JSON for free
Next up: Testing with curl — your API toolbox