🎓 A1Learner
🔍
0 of 50 lessons completed

Lists of Objects as JSON

A list of objects is a JSON array of objects. Each object in the array holds the fields of one item.

Return a list from a route

The method returns three tasks. Jackson turns them into one array.

@GetMapping("/tasks")
public List<Task> tasks() {
    return List.of(new Task("Buy milk", false), new Task("Ship Spring Boot", true), new Task("Read a book", false));
}

An empty list

A list with no items becomes an empty array.

@GetMapping("/tasks")
public List<Task> tasks() {
    return List.of();
}

Example

import java.util.List;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TaskController {

    record Task(String title, boolean done) {
    }

    @GetMapping("/tasks")
    public List<Task> tasks() {
        return List.of(new Task("Buy milk", false), new Task("Ship Spring Boot", true), new Task("Read a book", false));
    }
}

Key points

  • Jackson is the library that turns Java objects into JSON.
  • Jackson turns a Java list into a JSON array.
  • Each list item becomes one object in the array.
  • The array keeps the order of the list.
  • A record gives every object the same fields.

In this example, the Task record holds a title and a done flag. The controller holds one route. The route answers GET /tasks. The method returns a list of three tasks. Jackson turns the list into a JSON array. The array keeps the order of the list.

Note

An empty list becomes an empty array.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does Jackson turn a Java list into?