public record UserResponseDTO(String name, int age) {} @RestController public class UserController { @GetMapping("/user") public UserResponseDTO getUser() { return new UserResponseDTO("Alice", 30); } }
The record UserResponseDTO has two fields: name and age. Spring Boot uses Jackson to convert this record to JSON, including both fields with their exact types. So the JSON output includes both name as a string and age as a number.
Option A tries to add a no-argument constructor to a record, which is not allowed in Java records. Records automatically generate a canonical constructor with all components. Adding a no-arg constructor causes a compilation error.
public record Address(String street, String city) {}
public record UserResponseDTO(String name, Address address) {}
@RestController
public class UserController {
@GetMapping("/user")
public UserResponseDTO getUser() {
Address addr = new Address("123 Main St", "Springfield");
return new UserResponseDTO("Bob", addr);
}
}The nested Address record is serialized as a JSON object inside the address property. Both street and city fields appear in the nested JSON.
public class EmptyResponseDTO { private String data; public String getData() { return data; } } @RestController public class TestController { @GetMapping("/test") public EmptyResponseDTO getTest() { EmptyResponseDTO dto = new EmptyResponseDTO(); dto.data = "Hello"; return dto; } }
Jackson serializes Java objects to JSON by calling public getters or accessing fields with proper annotations. Since 'data' is private and no getter is provided, Jackson sees no properties to serialize, resulting in an empty JSON object.
Spring Boot uses the Jackson library by default to convert returned objects from controller methods into JSON when the client requests JSON. This happens automatically without needing extra annotations on fields.