我正在寻找仅在某些情况下序列化瞬态信息的可能性:
@JsonInclude(Include.NON_NULL)
@Entity
public class User {
public static interface AdminView {}
... id, email and others ...
@Transient
private transient Details details;
@JsonIgnore // Goal: ignore all the time, except next line
@JsonView(AdminView.class) // Goal: don't ignore in AdminView
public Details getDetails() {
if (details == null) {
details = ... compute Details ...
}
return details;
}
}
public class UserDetailsAction {
private static final ObjectWriter writer = new ObjectMapper();
private static final ObjectWriter writerAdmin = writer
.writerWithView(User.AdminView.class);
public String getUserAsJson(User user) {
return writer.writeValueAsString(user);
}
public String getUserAsJsonForAdmin(User user) {
return writerAdmin.writeValueAsString(user);
}
}
如果我调用 getUserAsJson,我希望看到 id、email 和其他字段,但不会看到详细信息。这工作正常。但我对 getUserAsJsonForAdmin 也看到了同样的情况,也没有详细说明。如果我删除 @JsonIgnore 注释 - 我确实会在两个调用中看到详细信息。
我做错了什么,有什么好的方法吗?谢谢!