
@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;
<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
}以上就是在Java中使用Jackson时何时使用@ConstructorProperties注解?的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号