How to Return JSON Responses in Spring REST APIs

How to Return JSON Responses in Spring REST APIs

Spring Boot makes it easy to return JSON responses from REST controllers. Whether you're returning a single object, a list of objects, or custom messages, Spring handles the serialization and response creation seamlessly.

1. Return Object Directly

When you annotate your class with @RestController, Spring automatically converts your returned object to JSON.

@RestController
@RequestMapping("/api/employees")
public class EmployeeController {

    @GetMapping("/{id}")
    public Employee getEmployee(@PathVariable Long id) {
        return new Employee(id, "John", "Doe", "john@example.com");
    }
}

2. Use ResponseEntity for More Control

ResponseEntity allows you to control status codes, headers, and body.

@GetMapping("/{id}")
public ResponseEntity<Employee> getEmployee(@PathVariable Long id) {
    Employee emp = new Employee(id, "John", "Doe", "john@example.com");
    return ResponseEntity.ok(emp);
}

3. Return Lists or Arrays

You can return lists and Spring will convert them to a JSON array.

@GetMapping
public List<Employee> getAllEmployees() {
    return Arrays.asList(
        new Employee(1L, "Alice", "Smith", "alice@example.com"),
        new Employee(2L, "Bob", "Brown", "bob@example.com")
    );
}

4. Create a Custom JSON Response Wrapper

Use a wrapper to include metadata like status, message, or timestamp.

public class ApiResponse<T> {
    private String status;
    private String message;
    private T data;

    public ApiResponse(String status, String message, T data) {
        this.status = status;
        this.message = message;
        this.data = data;
    }

    // Getters and setters...
}
Then return it in your controller:
@GetMapping("/{id}")
public ResponseEntity<ApiResponse<Employee>> getEmployee(@PathVariable Long id) {
    Employee emp = new Employee(id, "John", "Doe", "john@example.com");
    ApiResponse<Employee> response = new ApiResponse<>("success", "Employee found", emp);
    return ResponseEntity.ok(response);
}

5. Handle Errors Gracefully

Use @ControllerAdvice and @ExceptionHandler to return JSON error responses.

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(EmployeeNotFoundException.class)
    public ResponseEntity<ApiResponse<String>> handleNotFound(EmployeeNotFoundException ex) {
        ApiResponse<String> response = new ApiResponse<>("error", ex.getMessage(), null);
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
    }
}

6. Sample Employee Class

Used in our examples:

public class Employee {
    private Long id;
    private String firstName;
    private String lastName;
    private String email;

    // Constructor, Getters, Setters
}

Conclusion

Spring Boot provides multiple ways to return clean, customizable JSON responses. Whether you want to send plain objects or detailed API responses with metadata, Spring has you covered. Use ResponseEntity and wrapper classes for more structured APIs.

🔄 Master JSON Responses in Spring Boot

Returning JSON responses is the foundation of REST API development in Spring Boot. Strengthen your understanding of controllers, validation, and API design by exploring these closely related topics.

🌐 Controller vs RestController

Understand how @RestController simplifies returning JSON responses.

🏷️ Spring Boot Annotations for REST APIs

Learn how @ResponseBody, @RequestBody, and mapping annotations work.

✅ REST API Validation Annotations

Validate incoming request payloads before returning JSON responses.

🧩 Custom Validation Annotations

Build reusable validators for clean and consistent API responses.

🚨 Global Exception Handling

Return consistent JSON error responses using @ControllerAdvice.

🧩 Spring Boot CRUD API Example

See JSON responses in action within a real-world CRUD REST API.

📘 Spring Boot JPA Basics

Learn how JPA entities are serialized into JSON responses.

🎓 Spring Boot Interview Questions (Freshers)

Common interview questions on JSON responses and REST controllers.

💼 Spring Boot Interview Questions (2–5 Years)

Real-world interview discussions on REST API response design.