English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

When to Use @ConstructorProperties Annotation in Java's Jackson?

@ConstructorPropertiesAnnotation is fromjava.beanSmall package for deserializing JSON to Java objects Annotate the constructor. This annotation is fromJackson 2.7VersionStarting support. The operation of this annotation is very simple, instead of annotating each parameter in the constructor, we can provide the property name of each constructor parameter for the array.

Syntax

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

Beispiel

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);
   {}
{}
//Mitarbeiter-Schicht
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;
   {}
{}

Ausgabefolge

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