何時在 Java 中將 @ConstructorProperties 註解與 Jackson 一起使用?
@ConstructorProperties 註解來自 java.beans 包,用於透過帶註解的建構函式將 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 }
廣告