Line At A Time
Lesson 6: A JSON Menu
A JSON Menu Return a whole list of objects as a JSON array.
1import java.util.List;
2import org.springframework.web.bind.annotation.*;
3
4record Pizza(String name, int slices) {}
5
6@RestController
7public class MenuController {
8 @GetMapping("/menu")
9 public List<Pizza> menu() {
10 return List.of(
11 new Pizza("Margherita", 8),
12 new Pizza("Pepperoni", 8));
13 }
14}
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/menu
[{"name":"Margherita","slices":8},{"name":"Pepperoni","slices":8}]
Every line, explained
import java.util.List;
List comes from the standard library, not from Spring: frameworks and plain Java mix freely.
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) {}
The same one-line data class as last lesson. (In a real project Pizza would live in its own file and both controllers would share it; it is repeated here so this lesson stands on its own.)
@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 MenuController {
A controller is a perfectly ordinary Java class; the annotations are what make it special.
@GetMapping("/menu")
One endpoint for the whole menu.
public List<Pizza> menu() {
The return type is List<Pizza>: a list where every item is a Pizza. The angle brackets say what the list holds.
return List.of(
List.of(...) builds a fixed list from the items you give it. The ( stays open: the items follow on the next lines.
new Pizza("Margherita", 8),
First item. The comma means another item follows.
new Pizza("Pepperoni", 8));
Last item. Its ) closes new Pizza, the next ) closes List.of, and the ; ends the return statement. Spring converts the whole list to a JSON array: square brackets around the items. This is exactly the shape of response a real menu app would fetch.
}
This } closes the method.
}
This } closes the class.