Computer >> Máy Tính >  >> Lập trình >> Java

Khi nào sử dụng chú thích @ConstructorProperties với Jackson trong Java?


@ConstructorProperties chú thích đến từ java.bean gói s, được sử dụng để giải mã JSON thành đối tượng java thông qua phương thức tạo chú thích . Chú thích này hỗ trợ từ phiên bản Jackson 2.7 trở đi. Cách thức hoạt động của chú thích này rất đơn giản, thay vì chú thích từng tham số trong hàm tạo, chúng tôi có thể cung cấp một mảng với tên thuộc tính cho từng tham số của hàm tạo.

Cú pháp

@Documented
@Target(value=CONSTRUCTOR)
@Retention(value=RUNTIME)
public @interface ConstructorProperties

Ví dụ

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;
   }
}

Đầu ra

{
 "empName" : "Raja",
 "empId" : 115
}