Jackson Annotations - @JsonView



Overview

@JsonView annotation is used to control values to be serialized or not.

How to use @JsonView

Define Views

class Views {
   static class Public {}
   static class Internal extends Public {}
}

Annotate Properties with @JsonView

Here we've defined two scopes as Public and Internal. Now we'll control our serialization of values using @JsonView annotation.

class Student {
   @JsonView(Views.Public.class)
   public int id;
   @JsonView(Views.Public.class)
   public String name;
   @JsonView(Views.Internal.class)
   public int age;
   ...
}

Serialize using required View defined above.

Now, during serialization, we can define using View, here Views.Public as which properties are to be serialized.

String jsonString = mapper
         .writerWithDefaultPrettyPrinter()
         .withView(Views.Public.class)
         .writeValueAsString(student);

Example - Serialization with @JsonView

JacksonTester.java

package com.tutorialspoint;

import java.io.IOException;
import java.text.ParseException;
import com.fasterxml.jackson.annotation.JsonView;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonTester {
   public static void main(String args[]) throws IOException, ParseException {
      ObjectMapper mapper = new ObjectMapper();     
      Student student = new Student(1, "Mark", 12);
      String jsonString = mapper
         .writerWithDefaultPrettyPrinter()
         .withView(Views.Public.class)
         .writeValueAsString(student);
      System.out.println(jsonString);
   }
}
class Student {
   @JsonView(Views.Public.class)
   public int id;
   @JsonView(Views.Public.class)
   public String name;
   @JsonView(Views.Internal.class)
   public int age;

   Student(int id, String name, int age) {
      this.id = id;
      this.name = name;
      this.age = age;
   }
}
class Views {
   static class Public {}
   static class Internal extends Public {}
}

Output

Run the JacksonTester and verify the output −

{
  "id" : 1,
  "name" : "Mark"
}

Here we can see, using @JsonView annotation, we're able to control serialization of properties.

Advertisements