I'm looking for possibility to serialize transient information only in some cases:
@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);
}
}
If I call getUserAsJson I expected to see id, email and other fields, but not details. This works fine. But I see same for getUserAsJsonForAdmin, also without detail. If I remove @JsonIgnore annotation - I do see details in both calls.
What do I wrong and is there good way to go? Thanks!