Close

Jackson JSON - Using @JsonUnwrapped to serialize/deserialize properties as flattening data structure

[Last Updated: Aug 11, 2020]

JsonUnwrapped is used to indicate that a property should be serialized unwrapped, i.e. the target property will not be serialized as JSON object but its properties will be serialized as flattened properties of its containing Object. Let's understand that with an example.

Example

Java Objects

package com.logicbig.example;

public class Department {
  private String deptName;
  private String location;
    .............
}
package com.logicbig.example;

import com.fasterxml.jackson.annotation.JsonUnwrapped;

public class Employee {
  private String name;
  @JsonUnwrapped
  private Department dept;
    .............
}

Main class

public class ExampleMain {
  public static void main(String[] args) throws IOException {
      Department dept = new Department();
      dept.setDeptName("Admin");
      dept.setLocation("NY");
      Employee employee = new Employee();
      employee.setName("Amy");
      employee.setDept(dept);

      System.out.println("-- before serialization --");
      System.out.println(employee);

      System.out.println("-- after serialization --");
      ObjectMapper om = new ObjectMapper();
      String jsonString = om.writeValueAsString(employee);
      System.out.println(jsonString);

      System.out.println("-- after deserialization --");
      Employee employee2 = om.readValue(jsonString, Employee.class);
      System.out.println(employee2);
  }
}
-- before serialization --
Employee{name='Amy', dept=Department{deptName='Admin', location='NY'}}
-- after serialization --
{"name":"Amy","deptName":"Admin","location":"NY"}
-- after deserialization --
Employee{name='Amy', dept=Department{deptName='Admin', location='NY'}}

Without @JsonUnwrapped

If we remove @JsonUnwrapped from 'dept' property of Employee class then output will be:

-- before serialization --
Employee{name='Amy', dept=Department{deptName='Admin', location='NY'}}
-- after serialization --
{"name":"Amy","dept":{"deptName":"Admin","location":"NY"}}
-- after deserialization --
Employee{name='Amy', dept=Department{deptName='Admin', location='NY'}}

Example Project

Dependencies and Technologies Used:

  • jackson-databind 2.9.6: General data-binding functionality for Jackson: works on core streaming API.
  • JDK 10
  • Maven 3.5.4

@JsonUnwrapped Example Select All Download
  • jackson-json-wrapped-annotation-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • Employee.java

    See Also