Java Jackson @JsonView Example

1. Introduction

Jackson's @JsonView annotation provides a way to define different views of a Java Object. With this, you can control which properties of an object need to be serialized into JSON based on different views. This is extremely useful when you want to restrict certain fields from being serialized in different scenarios, such as public vs. internal API views.

2. Example Steps

1. Define different view classes to represent different serialization views.

2. Create a User class with properties id, name, and address, and annotate them with the respective views.

3. Serialize the User object using different views.

4. Print the output to observe which properties are included for each view.

3. Java Jackson @JsonView Example

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.annotation.JsonView;

public class JsonViewExample {

    // Define view classes
    public static class PublicView {}
    public static class InternalView extends PublicView {}

    public static class User {
        @JsonView(PublicView.class)
        private int id;

        @JsonView(PublicView.class)
        private String name;

        @JsonView(InternalView.class)
        private String address;

        public User(int id, String name, String address) {
            this.id = id;
            this.name = name;
            this.address = address;
        }
    }

    public static void main(String[] args) throws Exception {
        User user = new User(1, "John Doe", "123 Elm St.");

        ObjectMapper mapper = new ObjectMapper();

        // Serialize using public view
        String publicView = mapper.writerWithView(PublicView.class).writeValueAsString(user);
        System.out.println("Public View: " + publicView);

        // Serialize using internal view
        String internalView = mapper.writerWithView(InternalView.class).writeValueAsString(user);
        System.out.println("Internal View: " + internalView);
    }
}

Output:

Public View: {"id":1,"name":"John Doe"}
Internal View: {"id":1,"name":"John Doe","address":"123 Elm St."}

4. Step By Step Explanation

The @JsonView annotation helps in serializing different views of an object. We've defined two views: PublicView and InternalView (where InternalView extends PublicView).

In the User class, the id and name properties are tagged with PublicView, indicating they should be included in any serialization that uses this view. The address property, however, is tagged with InternalView, making it exclusive to this view.

In the main method, when we serialize using the PublicView, only id and name are included. But when we serialize using the InternalView, all properties (id, name, and address) are included since InternalView extends PublicView and hence includes its properties too.


Comments