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

Solution 1:

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

@JsonView(User.Views.Public.class)
    public String getFirstname() {
        return firstname;
    }

 @JsonView(User.Views.Public.class)
    public String getLastname() {
        return lastname;
    }

Message Pojo class

@JsonView(User.Views.Internal.class)
    public List<Message> getMessages() {
        return messages;
    }

Rest controller

@RestController
public class SimpleRestController {

    @Autowired
    SimpleService simpleService;

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


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