Search code examples
javajsonspringjacksonjackson2

Wrapping Json fields into instance variable of a pojo


i am trying to map certain json fields to a class instance variable.

My sample Person class looks like:

public class Person {
   private String name;
   private Address address;

   //many more fields 

   //getters and setters
}

The sample Address class is:

public class Address {
   private String street;
   private String city;
   //many more fields 

   // getters and setters
}

The json object to be deserialized to my Person class doesn't contain "address" field. It looks like:

{
"name":"Alexander",
"street":"abc 12",
"city":"London"
}

Is there a way to deserialize the json to the Person pojo where the Address fields are also mapped properly?

I have used a custom Address deserializer as mentioned in so many posts here. However, it's not being called as the Json object doesn't contain "address" field.

I had resolved this problem by mapping each field manually using JsonNode, however in my real project, it's not a nice solution.

Is there any work around for such problem using jackson? Plus if this question has been asked before then apologies on my behalf as as i have intensively searched for the solution and might have not seen it yet. .


Solution

  • @JsonUnwrapped annotation was introduced for this problem. Model:

    class Person {
        private String name;
    
        @JsonUnwrapped
        private Address address;
    
        // getters, setters, toString
    }
    class Address {
        private String street;
        private String city;
    
        // getters, setters, toString
    }
    

    Usage:

    ObjectMapper mapper = new ObjectMapper();
    String json = "{\"name\":\"Alexander\",\"street\":\"abc 12\",\"city\":\"London\"}";
    System.out.println(mapper.readValue(json, Person.class));
    

    Prints:

    Person{name='Alexander', address=Address{street='abc 12', city='London'}}
    

    For more info read:

    1. Jackson Annotation Examples
    2. Annotation Type JsonUnwrapped
    3. Jackson JSON - Using @JsonUnwrapped to serialize/deserialize properties as flattening data structure