2

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.

psi_
  • 65
  • 5

1 Answers1

2

Generic names

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.

Inheritance

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).

cassiomolin
  • 124,154
  • 35
  • 280
  • 359
  • Thanks! I think using _generic names_ as you said is a better choice, now I need to figure it out which is the best approach for my API. Do you know any others JSON apis that provide something like @JsonView? – psi_ Nov 07 '17 at 10:36
  • @psi_ Gson is another popular JSON parser for Java, but I'm not sure if it provider something like JSON views. – cassiomolin Nov 07 '17 at 10:40
  • @psi_ If my answer works for you, please click the tick next to my answer to mark it as accepted. – cassiomolin Nov 07 '17 at 10:40
  • Sorry, I forgot.. hahaha – psi_ Nov 09 '17 at 19:43