คำอธิบายประกอบ @ConstructorProperties มาจากแพ็กเกจ java.beans ใช้สำหรับถอดรหัส (deserialize) 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
}