Java and @JsonProperty



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

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类将具有@JsonProperty,而不是Person类。

谢谢。

使用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 ...
}

用@JsonProperty 覆盖getter方法

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

最新更新