嗨,我有几个互相嵌入的UI对象。范例1:
class CarUI {
public UserUI user;
public UserUI agent;
....
public UserUI getUser() {
return user;
}
public UserUI getAgent() {
return agent;
}
}
class UserUI {
@JsonView({Views.Public.class,Views.Private.class})
public String name;
@JsonView({Views.Private.class})
public String phone;
...
}
如您所见,如果我将UserUI序列化为Public,则仅公开名称,而对于private,则公开所有字段。
这是我的问题:序列化对象CarUI时,我只想公开“用户”的名称,而只公开“代理”的名称和电话。从本质上讲,这意味着在getUser()的getter中,我想将JsonView更改为Views.Public.class,对于getAgent(),我想将其更改为Views.Private.class
有没有办法在getter中覆盖JsonView,以使返回对象的所有层次结构现在都可以使用此新JsonView进行序列化?
编辑
如下所述,您可以使用JsonView继承解决我的Example#1。那更通用。这是示例2:
class CarUI {
public UserUI user;
public UserUI agent;
....
public UserUI getUser() {
return user;
}
public UserUI getAgent() {
return agent;
}
}
class UserUI {
@JsonView({Views.Public.class,Views.Private.class})
public String name;
@JsonView({Views.Private.class})
public String phone;
@JsonView({Views.Public.class})
public String avatarUrl;
...
}
在此示例中,Id希望为Agent显示name + phone,为User显示name + avatarUrl。
最佳答案
@JsonView接受继承。 Views.Private字段扩展了Views.Public字段。这意味着Views.Private序列化还将查找Views.Public批注。
public Views {
public Public {}
public Private extends Public {}
}
class CarUI {
public UserUI user;
public UserUI agent;
....
@JsonView(Views.Public.class)
public UserUI getUser() {
return user;
}
@JsonView(Views.Private.class)
public UserUI getAgent() {
return agent;
}
}
class UserUI {
@JsonView(Views.Public.class)
public String name;
@JsonView(Views.Private.class)
public String phone;
...
}
例如#2
您可以引入多个类,例如:
public Views {
public Public {}
public Private1 extends Public {}
public Private2 extends Public {}
}
class CarUI {
public UserUI user;
public UserUI agent;
....
public UserUI getUser() {
return user;
}
public UserUI getAgent() {
return agent;
}
}
class UserUI {
@JsonView(Views.Public.class)
public String name;
@JsonView({Views.Private1.class})
public String phone;
@JsonView({Views.Private2.class})
public String avatarUrl;
...
}
或者,您可以使用无视图属性并且不使用继承:
public Views {
public Public {}
public Private {}
}
class CarUI {
public UserUI user;
public UserUI agent;
....
public UserUI getUser() {
return user;
}
public UserUI getAgent() {
return agent;
}
}
class UserUI {
// This one is view-less shows every time unless you specificy
public String name;
@JsonView({Views.Private.class})
public String phone;
@JsonView({Views.Public.class})
public String avatarUrl;
...
}
...
// If you want to hide view-less properties, default is true
objectMapper.configure(SerializationConfig.Feature.DEFAULT_VIEW_INCLUSION, false);
...