implementing Jackson Deserialization of Nested JSON to Java Objects with Optional Fields
I'm optimizing some code but Quick question that's been bugging me - I'm stuck on something that should probably be simple. I'm working with a scenario with deserializing a nested JSON structure into Java objects using Jackson in my Spring Boot application. My JSON sometimes omits certain nested fields, which I have defined as `Optional` in my Java classes. The JSON looks like this: ```json { "name": "John Doe", "address": { "city": "New York" } } ``` Here, the `address` object is optional and can sometimes be entirely absent in the JSON. My Java class setup is as follows: ```java import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.ObjectMapper; import java.util.Optional; @JsonInclude(JsonInclude.Include.NON_NULL) public class User { private String name; private Optional<Address> address; // Getters and Setters } @JsonInclude(JsonInclude.Include.NON_NULL) public class Address { private String city; // Getters and Setters } ``` I've tried using `@JsonInclude(JsonInclude.Include.NON_NULL)` to skip null fields, but I'm still getting a `com.fasterxml.jackson.databind.JsonMappingException` when the `address` field is missing from the JSON. The exception message states: ``` want to deserialize value of type `Optional` from Object value (token `JsonToken.START_OBJECT`). ``` I've also made sure that I'm using Jackson version 2.12.3, and my ObjectMapper is configured like this: ```java ObjectMapper objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); ``` Is there a correct way to handle optional nested fields during deserialization? I want the `address` field to be set as `Optional.empty()` when it isn't present in the JSON. Any help would be greatly appreciated! For context: I'm using Java on Linux. The project is a microservice built with Java. Any advice would be much appreciated.