Close

Jackson JSON - Using prefix and suffix attributes of @JsonUnwrapped to avoid name collisions

[Last Updated: Aug 11, 2020]

In the last tutorial we saw how to use @JsonUnwrapped annotation. This tutorial shows how attributes @JsonUnwrapped#prefix and @JsonUnwrapped#suffix can be used to avoid name collision.

Example

Java Object

public class Department {
    private String name;
    private String location;
    .............
}
public class Employee {
    private String name;
    @JsonUnwrapped(prefix = "dept-")
    private Department dept;
    .............
}

As seen above, Employee and Department classes have same named properties 'name'. To prevent collision, we used 'prefix' attribute in Employee class.

Main class

public class ExampleMain {
    public static void main(String[] args) throws IOException {
        Department dept = new Department();
        dept.setName("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{name='Admin', location='NY'}}
-- after serialization --
{"name":"Amy","dept-name":"Admin","dept-location":"NY"}
-- after deserialization --
Employee{name='Amy', dept=Department{name='Admin', location='NY'}}

Without prefix or suffix attributes

Let's remove prefix attribute in Employee class:

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

In this case output will be:

-- before serialization --
Employee{name='Amy', dept=Department{name='Admin', location='NY'}}
-- after serialization --
{"name":"Amy","name":"Admin","location":"NY"}
-- after deserialization --
Employee{name='Admin', dept=Department{name='null', 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

Using @JsonUnwrapped#prefix and @JsonUnwrapped#suffix Select All Download
  • jackson-json-unwrapped-using-prefix-suffix
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • Employee.java

    See Also