English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

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);
   {}
{}
//従業員階級
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
{}