Main Tutorials

Jackson @JsonView examples

In Jackson, we can use the annotation @JsonView to control which fields of the same resource are displayed for different users.

Table of contents:

P.S Tested with Jackson 2.17.0

1. Download Jackson

Declare jackson-databind in the pom.xml, and it will automatically pull in jackson-annotations, jackson-core, and other necessary dependencies.

pom.xml

  <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.17.0</version>
  </dependency>

2. Define View Classes

This example defines three view classes: Normal, Manager, and HR; each view will see different JSON properties.

ViewCompany.java

package com.mkyong.json.jackson.jsonviews;

public class ViewCompany {

    public static class Normal{};
    public static class Manager extends Normal{};
    public static class HR extends Normal{};

}

Here, Manager extends Normal, which means whatever is visible in the Normal view is also visible in the Manager view.

3. Annotate model class with @JsonView

Annotate the model class with @JsonView to specify which view they belong to:

Three Views

  • Normal – name, age, active
  • Manager – name, age, active, position, skills
  • HR – name, age, active, position, salary
Staff.java

package com.mkyong.json.jackson.jsonviews;

import com.fasterxml.jackson.annotation.JsonView;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class Staff {

    @JsonView(ViewCompany.Normal.class)
    private String name;

    @JsonView(ViewCompany.Normal.class)
    private int age;

    @JsonView({ViewCompany.HR.class, ViewCompany.Manager.class})
    private String[] position;              

    @JsonView(ViewCompany.Manager.class)
    private List<String> skills;            

    @JsonView(ViewCompany.HR.class)
    private Map<String, BigDecimal> salary;

    @JsonView(ViewCompany.Normal.class)
    private boolean active;

    //getters, setters, constructors
}

4. Testing the Jackson @JasonView

In the Jackson ObjectMapper object, we can use ObjectMapper.writerWithView(view_class) to apply view during serialization.

JsonViewExample.java

package com.mkyong.json.jackson.jsonviews;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class JsonViewExample {

    public static void main(String[] args) {

        ObjectMapper mapper = new ObjectMapper();

        Staff staff = createStaff();

        try {

            // to enable pretty print
            mapper.enable(SerializationFeature.INDENT_OUTPUT);

            // normal
            String normalView = mapper
                    .writerWithView(ViewCompany.Normal.class)
                    .writeValueAsString(staff);

            System.out.format("\nNormal view\n%s\n", normalView);

            // manager
            String managerView = mapper
                    .writerWithView(ViewCompany.Manager.class)
                    .writeValueAsString(staff);

            System.out.format("\nManager view\n%s\n", managerView);

            // hr
            String hrView = mapper
                    .writerWithView(ViewCompany.HR.class)
                    .writeValueAsString(staff);

            System.out.format("\nHR view\n%s\n", hrView);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    private static Staff createStaff() {

        Staff staff = new Staff();

        staff.setName("mkyong");
        staff.setAge(42);
        staff.setPosition(new String[]{"Founder", "CTO", "Writer", "Minimalists"});

        Map<String, BigDecimal> salary = new HashMap<>();
        salary.put("2010", new BigDecimal(10000));
        salary.put("2012", new BigDecimal(12000));
        salary.put("2018", new BigDecimal(14000));
        staff.setSalary(salary);

        staff.setSkills(Arrays.asList("java", "python", "node", "kotlin"));

        return staff;

    }

}

Output


Normal view
{
  "name" : "mkyong",
  "age" : 42,
  "active" : false
}

Manager view
{
  "name" : "mkyong",
  "age" : 42,
  "position" : [ "Founder", "CTO", "Writer", "Minimalists" ],
  "skills" : [ "java", "python", "node", "kotlin" ],
  "active" : false
}

HR view
{
  "name" : "mkyong",
  "age" : 42,
  "position" : [ "Founder", "CTO", "Writer", "Minimalists" ],
  "salary" : {
    "2018" : 14000,
    "2012" : 12000,
    "2010" : 10000
  },
  "active" : false
}

5. Download Source Code

$ git clone https://github.com/mkyong/java-json

$ cd jackson

6. References

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments