GET Endpoints that Return JSON
Return a Java object or list from a controller and Spring turns it into JSON automatically — the heart of any API.
What you will learn
- Return an object as JSON
- Return a list as a JSON array
- Understand automatic conversion
Why JSON?
JSON is the standard text format APIs use to send data. It looks like simple labelled values. The best part in Spring Boot: if your method returns a Java object, Spring converts it to JSON for you — you write zero conversion code.
Return an object
Make a small class to hold data, then return it from a controller method:
// A simple data class (a "model")
public class Product {
private int id;
private String name;
private double price;
public Product(int id, String name, double price) {
this.id = id; this.name = name; this.price = price;
}
// getters are needed so Spring can read the fields
public int getId() { return id; }
public String getName() { return name; }
public double getPrice() { return price; }
}
@RestController
public class ProductController {
@GetMapping("/product")
public Product one() {
return new Product(1, "Keyboard", 799.0);
}
}Note: Output (visiting /product): {"id":1,"name":"Keyboard","price":799.0} Spring read the getters and turned the object into JSON automatically. The field names become the JSON keys.
Return a list
Return a List and Spring sends back a JSON array:
@GetMapping("/products")
public List<Product> all() {
return List.of(
new Product(1, "Keyboard", 799.0),
new Product(2, "Mouse", 499.0)
);
}Note: Output (visiting /products): [{"id":1,"name":"Keyboard","price":799.0}, {"id":2,"name":"Mouse","price":499.0}] A Java List becomes a JSON array, and each Product becomes a JSON object inside it.
Tip: Spring needs getters to read your object’s fields. If your JSON comes back empty (just two curly braces), missing getters are almost always the reason.
Watch out: Do not put passwords or other secret fields on objects you return — whatever the object exposes through getters ends up in the JSON the client can see.
Q. You return a Java List of objects from a GET method. What does the client receive?
✍️ Practice
- Create a
Bookclass (id, title, author) and a/bookendpoint that returns one. - Add a
/booksendpoint that returns a list of three books as JSON.
🏠 Homework
- Build a
/studentsendpoint that returns a list of student objects (id, name, course) as JSON.