我有这两个课程Human
,User
它们看起来像:
public class User{
@JsonView(ExternalCategoriesViews.CustomCategoryExternalView.class)
protected Long id;
@JsonView(ExternalCategoriesViews.CustomCategoryExternalView.class)
protected String firstname;
@JsonView(ExternalCategoriesViews.CustomCategoryExternalView.class)
protected String lastname;
protected String email;
protected String address;
protected String postalCode;
@JsonView(ExternalCategoriesViews.CustomCategoryExternalView.class)
protected String city;
protected String country;
public User(Long id, String firstname, String lastname, String email, String address,
String postalCode, String city, String country) {
this.id = id;
this.firstname = firstname;
this.lastname = lastname;
this.email = email;
this.address = address;
this.postalCode = postalCode;
this.city = city;
this.country = country;
}
}
public class Human extends User {
String sex;
@JsonView({ExternalCategoriesViews.CustomCategoryExternalView.class})
String salary;
public Human(Long id, String firstname, String lastname, String email, String address,
String postalCode, String city, String country, String sex, String salary) {
super(id, firstname, lastname, email, address, postalCode, city, country);
this.sex = sex;
this.salary = salary;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getSalary() {
return salary;
}
public void setSalary(String salary) {
this.salary = salary;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
Human human = (Human) o;
return Objects.equals(salary, human.salary);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), salary);
}
}
我有一个返回的控制器Human
。
@RequestMapping(method = RequestMethod.GET,
value = "/test",
produces = MediaType.APPLICATION_JSON + "; charset=UTF-8")
@ResponseBody
@JsonView(ExternalCategoriesViews.CustomCategoryExternalView.class)
public Human getCustomCategory1() {
Human n = new Human(1L,"first name","last name", "w@c.c","address","qwe","city","country","male","12000");
return n;
}
我有这个用于 JsonView 的课程:
public class ExternalCategoriesViews {
public interface CustomCategoryExternalView {
}
}
这里的问题是,我期待的是得到没有“性”属性的响应,因为它没有用@JsonView
. 所以响应不应该包含它,但事实并非如此,因为我仍然看到它。
我注意到,如果我删除getSex()
getter,那么“sex”属性将从响应中消失,所以我可以说@JsonView
有效。
但不幸的是,我无法摆脱吸气剂。
然后我了解到@JsonView()
使用反射来访问私有和受保护的属性。删除 getter 后,Jackson 不知道如何序列化/反序列化属性,因此没有 getter@JsonView()
将正常工作,因为它无法访问属性,并且只有带有注释的那些@JsonView()
才会在序列化中考虑。
我的问题是,如何在@JsonView()
不移除 getter 的情况下使这个“性”属性从响应中消失(使工作正常)?