@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中文網其他相關文章!