Careeroza
Returning JSON
Return Objects, Get JSON
Return a Java object, a List or a Map and Jackson converts it to JSON automatically. Java records are ideal for API responses: short, immutable, and every component becomes a JSON field.
package com.shopease.product;
import java.math.BigDecimal;
public record Product(Long id, String name, String description,
BigDecimal price, int stock, String category) {}@RestController
@RequestMapping("/api/products")
public class ProductController {
private final List<Product> products = List.of(
new Product(1L, "Boat Rockerz 450", "Wireless headphones", new BigDecimal("1499.00"), 25, "Electronics"),
new Product(2L, "Clean Code", "Book by Robert C. Martin", new BigDecimal("599.00"), 40, "Books"));
@GetMapping
public List<Product> all() {
return products;
}
}The Response
Example
curl -s http://localhost:8080/api/productsExample output
[
{"id":1,"name":"Boat Rockerz 450","description":"Wireless headphones","price":1499.00,"stock":25,"category":"Electronics"},
{"id":2,"name":"Clean Code","description":"Book by Robert C. Martin","price":599.00,"stock":40,"category":"Books"}
]| Java type | JSON |
|---|---|
| record / class with getters | object { } |
List, array, Set | array [ ] |
Map<String, ?> | object |
String, numbers, boolean, null | JSON string, number, boolean, null |
LocalDate / LocalDateTime | ISO string, e.g. "2026-01-15" |
Practice
Exercise: Add GET /api/products/in-stock that returns only products with stock greater than 0.
Show answer
@GetMapping("/in-stock")
public List<Product> inStock() {
return products.stream()
.filter(p -> p.stock() > 0)
.toList();
}