IngeniousTom IngeniousTom - 10 months ago 96
Java Question

What is JSON View class in JACKSON and how it works?

I can't understand what is jackson's @JasonView(Views.MyClass.class).
I know that I can annotate POJO's fields and methods in this way to filter non-annotated ones from being serialized with JSON. But what it is (that View s.Myclass class)? Is it template class for jackson library or what? How should I descibe it in proper way?

And why there may be many classes inside the Views Class? For example like this:

class Views {
static class Public { }
static class ExtendedPublic extends PublicView { }
static class Internal extends ExtendedPublicView { }

Why it is needed and how it works?


@JsonView to filter fields depending on the context of serialization. When returning data to Rest client, depending on which Rest service was called, we need to limit which data will be serialized while using the same data model.

Lets say we want to create two Rest services.

The first Rest service would return some basic User information like its firstname and lastname but without the messages attached to it.

The second Rest Service would return all the informations from the first Rest service and also the messages attached to the current User.

Sample pojo classes with @JsonView annotation

User Pojo classs

    public String getFirstname() {
        return firstname;

    public String getLastname() {
        return lastname;

Message Pojo class

    public List<Message> getMessages() {
        return messages;

Rest controller

public class SimpleRestController {

    SimpleService simpleService;

    @RequestMapping(value = "/user/public", method = RequestMethod.GET)
    public User getUserWithPublicData() {
        return simpleService.loadUser();

    @RequestMapping(value = "/user/internal", method = RequestMethod.GET)
    public User getUserWithInternalData() {
        return simpleService.loadUser();