@ConstructorProperties注释是从java.bean小号包装,用于通过反序列化JSON到Java对象 注释构造。此注释从Jackson 2.7版本开始支持。此批注的工作方式非常简单,而不是对构造函数中的每个参数进行注释,我们可以为数组提供每个构造函数参数的属性名称。
@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); } } //员工阶层 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; } }
输出结果
{ "empName" : "Raja", "empId" : 115 }