在 Java 中,何时使用 Jackson 的 @ConstructorProperties 注释?
javajsonobject oriented programmingprogramming更新于 2025/7/26 9:48:17
@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);
}
}
// Employee class
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
}
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

