繁体   English   中英

Java 和@JsonProperty

[英]Java and @JsonProperty

我想知道是否有一种方法可以将 @JsonProperty 应用于 class 的继承字段。例如,我有以下类。

public class Person {
    protected String id;
    protected String firstName;
    protected String middleName;
    protected String lastName;
}

...

/**
 * need to figure out here, how to apply @JsonProperty
 * to the fields below of the parent class:
 * protected String id;
 * protected String firstName;
 * protected String middleName;
 * protected String lastName;
 */
public class Employee extends Person {
   @JsonProperty("DepartmentID")
   protected String departmentId;
}

这里的目标是只有 Employee class 会有 @JsonProperty 而不是 Person class。

谢谢。

使用 @JsonProperty 覆盖 getter 方法

   @JsonProperty("DepartmentID")
   protected String departmentId;
   @Override
   @JsonProperty("id")
   public String getId(){
     return super.getId();
   }
 // other getter methods
}

使用 getter 和 setter 并注释你的 getter 而不是字段。 Jackson会根据getter名称自动检测setter。

public class Person {
    private String id;
    private String firstName;
    private String middleName;
    private String lastName;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

   .. etc ...
}

public class Employee extends Person {
    @JsonProperty("id")
    @Override
    public String getId() {
        return super.getId();
    }

    ... etc ...
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM