CodexBloom - Programming Q&A Platform

Unexpected `NullPointerException` when accessing nested properties in a Java 17 REST API using Jackson

๐Ÿ‘€ Views: 77 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-08-26
java spring-boot jackson Java

I've been struggling with this for a few days now and could really use some help... I'm testing a new approach and I'm reviewing some code and I've searched everywhere and can't find a clear answer... I'm working with a `NullPointerException` when trying to serialize an object that contains nested properties in my Spring Boot application using Jackson. The scenario arises when my REST API returns a response that includes a complex object with optional fields. Hereโ€™s a simplified version of my class structure: ```java public class User { private String name; private Address address; // getters and setters } public class Address { private String street; private String city; private String country; // getters and setters } ``` In my controller, Iโ€™m returning a `User` object: ```java @GetMapping("/user/{id}") public ResponseEntity<User> getUser(@PathVariable Long id) { User user = userService.findById(id); return ResponseEntity.ok(user); } ``` The scenario surfaces when the `address` field of `User` is null, which leads to Jackson trying to serialize it and throwing a `NullPointerException`. I've also noticed that this only happens in certain conditions, possibly related to how the data is loaded from the database. To mitigate this, I tried adding `@JsonInclude(JsonInclude.Include.NON_NULL)` to the `User` class, but it didnโ€™t resolve the scenario. I also verified that my `UserService` returns the correct `User` object and that the database entries exist as expected. Here's the behavior trace Iโ€™m getting: ``` java.lang.NullPointerException: want to invoke "Address.getStreet()" because "user.getAddress()" is null ``` I am using Spring Boot 2.6.3 and Jackson 2.12.3, and I would like to know if there are any best practices to handle optional nested properties during serialization that could prevent this behavior from occurring. Is there a way to customize the serialization process for nested objects to avoid these exceptions? My development environment is Windows. What's the best practice here? I recently upgraded to Java 3.10. I'd really appreciate any guidance on this. My team is using Java for this application. Any suggestions would be helpful. I'd be grateful for any help.