Close

Jackson JSON - Using @ConstructorProperties to deserialize JSON via constructor

[Updated: Nov 20, 2018, Created: Nov 20, 2018]

Starting Jackson 2.7.0, java.beans.ConstructorProperties can also be used to deserialize JSON to Java Object via the annotated constructor.

Example

POJO

public class Employee {
  private String name;
  private String dept;

  @ConstructorProperties({"name", "dept"})
  public Employee(String name, String dept) {
      System.out.println("Constructor invoked");
      //Java 9 StackWalker to find out the caller
      System.out.println("caller: " + StackWalker.getInstance(
              StackWalker.Option.RETAIN_CLASS_REFERENCE).getCallerClass());
      this.name = name;
      this.dept = dept;
  }
    .............
}

Main class

public class ConstructorPropertiesExample {
  public static void main(String[] args) throws IOException {
      System.out.println("-- serializing --");
      Employee employee = new Employee("Trish", "Admin");
      //convert to json
      String jsonString = toJson(employee);
      System.out.println("serialized json: " + jsonString);

      System.out.println("-- deserializing --");
      Employee e = toEmployee(jsonString);
      System.out.println("deserialized object: " + e);
  }

  private static Employee toEmployee(String jsonData) throws IOException {
      ObjectMapper om = new ObjectMapper();
      return om.readValue(jsonData, Employee.class);
  }

  private static String toJson(Employee employee) throws IOException {
      ObjectMapper om = new ObjectMapper();
      return om.writeValueAsString(employee);
  }
}
-- serializing --
Constructor invoked
caller: class com.logicbig.example.ConstructorPropertiesExample
serialized json: {"name":"Trish","dept":"Admin"}
-- deserializing --
Constructor invoked
caller: class com.fasterxml.jackson.databind.introspect.AnnotatedConstructor
deserialized object: Employee{name='Trish', dept='Admin'}

Example Project

Dependencies and Technologies Used:

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

@ConstructorProperties Example Select All Download
  • jackson-constructor-properties
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • Employee.java

    See Also