Home  >  Article  >  Java  >  When to use @ConstructorProperties annotation when using Jackson in Java?

When to use @ConstructorProperties annotation when using Jackson in Java?

PHPz
PHPzforward
2023-08-27 20:53:051022browse

When to use @ConstructorProperties annotation when using Jackson in Java?

@ConstructorProperties The annotation comes from the java.bean package and is used to convert JSON through the annotated constructor. Serialized to java object. This annotation is supported starting with Jackson 2.7 version. The way this annotation works is very simple, instead of annotating each parameter in the constructor, we can provide an array containing the property names for each constructor parameter.

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;
<strong>   </strong>@ConstructorProperties({"id", "name"})<strong>
</strong>   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
}

The above is the detailed content of When to use @ConstructorProperties annotation when using Jackson in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete