When to use @ConstructorProperties annotation with Jackson in Java?


The @ConstructorProperties annotation is from java.beans package, used to deserialize JSON to java object via the annotated constructor. This annotation supports from Jackson 2.7 version onwards. The way this annotation works very simple, rather than annotating each parameter in the constructor, we can provide an array with the properties names for each of the constructor parameters.

Syntax

@Documented
@Target(value=CONSTRUCTOR)
@Retention(value=RUNTIME)
public @interface ConstructorProperties

Example

import com.fasterxml.jackson.databind.ObjectMapper;
import java.beans.ConstructorProperties;
public class ConstructorPropertiesAnnotationTest {
   public static void main(String args[]) throws Exception {
      ObjectMapper mapper = new ObjectMapper();
      Employee emp = new Employee(115, "Raja");
      String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(emp);
      System.out.println(jsonString);
   }
}
// Employee class
class Employee {
   private final int id;
   private final String name;
   @ConstructorProperties({"id", "name"})
   public Employee(int id, String name) {
      this.id = id;
      this.name = name;
   }
   public int getEmpId() {
      return id;
   }
   public String getEmpName() {
      return name;
   }
}

Output

{
 "empName" : "Raja",
 "empId" : 115
}

Updated on: 09-Jul-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements