>  기사  >  Java  >  Java에서 Jackson을 사용할 때 @ConstructorProperties 주석을 언제 사용해야 합니까?

Java에서 Jackson을 사용할 때 @ConstructorProperties 주석을 언제 사용해야 합니까?

PHPz
PHPz앞으로
2023-08-27 20:53:051022검색

Java에서 Jackson을 사용할 때 @ConstructorProperties 주석을 언제 사용해야 합니까?

@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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 tutorialspoint.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제