CodexBloom - Programming Q&A Platform

How to Handle Nested JSON Objects in a Spring Boot REST API Response?

šŸ‘€ Views: 0 šŸ’¬ Answers: 1 šŸ“… Created: 2025-06-14
spring-boot rest json hibernate Java

I'm stuck on something that should probably be simple. I'm currently working on a Spring Boot application where I need to return a nested JSON object in my REST API response. The structure looks something like this: ```json { "user": { "id": 1, "name": "John Doe", "address": { "street": "123 Main St", "city": "Anytown", "zipcode": "12345" } } } ``` I have a `User` class and an `Address` class set up like this: ```java @Entity public class User { @Id private Long id; private String name; @OneToOne(cascade = CascadeType.ALL) private Address address; // Getters and Setters } @Entity public class Address { @Id private Long id; private String street; private String city; private String zipcode; // Getters and Setters } ``` I created a repository and a service to fetch the user data, but when I hit the endpoint, I get a response that only contains the `User` fields, while the `address` field is returning as `null`. The controller method looks like this: ```java @RestController @RequestMapping("/api/users") public class UserController { @Autowired private UserService userService; @GetMapping("/{id}") public ResponseEntity<User> getUserById(@PathVariable Long id) { User user = userService.findById(id); return ResponseEntity.ok(user); } } ``` I have tried adjusting the `cascade` settings in the `@OneToOne` annotation and even attempted to use `@JsonIgnoreProperties` on the `Address` class to troubleshoot any serialization issues, but nothing seems to work. I also confirmed that the data in the database is correct and does include the `address` information. Could there be something I’m missing in the way I’m setting up the relationships or returning the response? Any help would be appreciated! I am using Spring Boot 2.5.4 and Hibernate 5.4.32.Final. I'm working on a service that needs to handle this. What am I doing wrong? For context: I'm using Java on Ubuntu 22.04. I'm working with Java in a Docker container on Windows 11.