When to use @ConstructorProperties annotation with Jackson in Java?



Jackson is a library that is used for converting Java objects to JSON and vice versa. It provides various annotations to customize the serialization and deserialization process. One such annotation is @ConstructorProperties, which is used to specify the properties of a constructor for deserialization.

The @ConstructorProperties annotation is from java.beans package, used to deserialize JSON to a Java object via the annotated constructor. If we use this annotation rather than annotating each parameter in the constructor, we can provide an array with the property names for each of the constructor parameters.

Let's learn when to use the @ConstructorProperties annotation with Jackson in Java.

When to Use @ConstructorProperties Annotation

The @ConstructorProperties annotation is particularly useful when you have a class with a constructor that takes multiple parameters, and you want to deserialize JSON into an instance of that class. It allows Jackson to map the JSON properties to the constructor parameters correctly.

Here's an example of how to use the @ConstructorProperties annotation with Jackson:

Example

In this example, the User class has a constructor annotated with @ConstructorProperties. The ObjectMapper from Jackson is used to deserialize a JSON string into a User object. The properties in the JSON are mapped to the constructor parameters based on the names specified in the annotation.

import com.fasterxml.jackson.databind.ObjectMapper;
import java.beans.ConstructorProperties;
public class User {
   private String name;
   private int age;

   @ConstructorProperties({"name", "age"})
   public User(String name, int age) {
      this.name = name;
      this.age = age;
   }

   // Getters
   public String getName() {
      return name;
   }

   public int getAge() {
      return age;
   }
}
public class Main {
   public static void main(String[] args) throws Exception {
      String json = "{"name":"Zoro", "age":23}";

      ObjectMapper objectMapper = new ObjectMapper();
      User user = objectMapper.readValue(json, User.class);

      System.out.println("User Name: " + user.getName());
      System.out.println("User Age: " + user.getAge());
   }
}

Following is the output of the above code:

User Name: Zoro
User Age: 23
Aishwarya Naglot
Aishwarya Naglot

Writing clean code… when the bugs aren’t looking.

Updated on: 2020-07-09T07:19:56+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements