IngeniousTom IngeniousTom - 3 years ago 163
Java Question

What is the JSON View class in Jackson and how does it work?

I don'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 is the Views.Myclass class? Is it a template class for Jackson library?

And why can there 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 is it needed and how does it work?

Answer Source

Use @JsonView to filter fields depending on the context of serialization. When returning data to a 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 service returns some user information like first name and last name but not the messages attached to it.

The second service returns all information from the first 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();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download