Line At A Time
Lesson 5: Returning JSON
Returning JSON Return an object and watch it become JSON automatically.
1import org.springframework.web.bind.annotation.*;
2
3record Pizza(String name, int slices) {}
4
5@RestController
6public class PizzaController {
7 @GetMapping("/pizza")
8 public Pizza pizza() {
9 return new Pizza("Margherita", 8);
10 }
11}
Terminal
$ ./mvnw spring-boot:run
:: Spring Boot :: (v3.3.0)
Tomcat started on port 8080 (http)
Started DemoApplication in 1.24 seconds
$ curl localhost:8080/pizza
{"name":"Margherita","slices":8}
Every line, explained
import org.springframework.web.bind.annotation.*;
This import brings in Spring's web annotations (@RestController, @GetMapping and friends). The .* means "everything in this package", which saves one import line per annotation.
record Pizza(String name, int slices) {}
A record is modern Java's shortcut for a class that just carries data: this one line gives you a Pizza class with a name, a slices count, a constructor, and a method to read each value back, like the classes you wrote in Your First Class but without the boilerplate. The {} means "and nothing else".
@RestController
@RestController is an annotation: a label that starts with @ and gives Spring information about your class. This one says "this class answers web requests, and whatever its methods return should be sent back to the caller". You never call this class yourself; Spring creates it and calls it for you.
public class PizzaController {
A controller is a perfectly ordinary Java class; the annotations are what make it special.
@GetMapping("/pizza")
Same annotation as before; the new trick is the return type below.
public Pizza pizza() {
The method returns a Pizza object, not a String. Servers mostly don't send sentences; they send structured data that apps and websites can unpack.
return new Pizza("Margherita", 8);
You return a plain Java object, and Spring converts it to JSON automatically: {"name":"Margherita","slices":8}. JSON is the universal packaging format of the web; every language can read it. This auto-conversion is a huge part of why frameworks save so much work.
}
This } closes the method.
}
This } closes the class.