I'm coding a Spring Web Service, using Jackson by default. I'm using @JsonView to indicate which property I need to be parsed to my JSON object. So, the problem is: Many objects are used in different classes, but not exactly all its properties, for example:
class Professor {
@JsonView({Views.Public.class, Views.Internal.class})
private int id;
@JsonView(Views.Internal.class)
private String name;
...
}
class Classroom {
@JsonView({Views.Public.class, Views.Internal.class})
private int id;
@JsonView(Views.Internal.class)
private String name;
...
}
class Lecture {
@JsonView(Views.Public.class)
private Professor professor;
@JsonView(Views.Public.class)
private Classroom classroom;
...
}
What if I need more than two 'perspectives', I'd have to create more interfaces/classes to do that? (like Views.Professor, Views.Principal, ...) Is this a real good practice?
I'd like to hear some suggestions or alternatives to solve that. I'm a little bit confused about being on the right track.
You always can define more views if you need more perspectives, that's the idea behind the Jackson JSON views and that's what makes it flexible.
If you use generic names in your views classes, such as Basic
, Extended
, Public
, Private
and so on, you'll find it easier to reuse them across multiple beans.
You always can rely on inheritance with @JsonView
. Consider the following example where Views.Private
extends Views.Public
:
public class Views {
interface Public {}
interface Private extends Public {}
}
Serialization of properties annotated with @JsonView(Views.Private.class)
will also include properties annotated with @JsonView(Views.Public.class)
.