Home >Java >javaTutorial >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.
@Documented @Target(value=CONSTRUCTOR) @Retention(value=RUNTIME) public @interface ConstructorProperties
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; } }
{ "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!