Importance of @JsonView annotation using Jackson in Java?



Jackson Library: The @JsonView Annotation

In Java, Jackson is a library that is used to convert JSON to Java objects and vice versa. Jackson Annotations are used during serialization and deserialization.

  • We use these to denote or specify annotations before a particular field or method (that is declared in Java).
  • Using an annotation before a field, we can denote whether a variable is a JsonProperty, should be ignored, or what condition should be applied to it.

The JsonView annotation is used to include/exclude a property during the serialization and deserialization. We need to configure an ObjectMapper class to include the type of view used for writing a JSON from a Java object using the writerWithView() method.

Example

This program serializes a Person object into JSON using the @JsonView annotation, on different views.
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonView;
import com.fasterxml.jackson.core.JsonProcessingException;
public class JsonViewAnnotationTest {
   public static void main(String args[]) throws JsonProcessingException {
      ObjectMapper objectMapper = new ObjectMapper();
      String jsonString = objectMapper.writerWithView(Views.Public.class).writeValueAsString(new Person());
      String jsonStringInternal = objectMapper.writerWithView(Views.Internal.class).writeValueAsString(new Person());
      System.out.println(jsonString);
      System.out.println(jsonStringInternal);
   }
}
// Person class
class Person {
   @JsonView(Views.Public.class)
   public long personId = 115;
   @JsonView(Views.Public.class)
   public String personName = "Raja Ramesh";
   @JsonView(Views.Internal.class)
   public String gender = "male";
   @Override
   public String toString() {
      return "Person{" +
             "personId=" + personId +
             ", personName='" + personName + ''' +
             ", gender='" + gender + ''' +
       '}';
   }
}
class Views {
   static class Public {}
   static class Internal extends Public {}
}

Output

{"personId":115,"personName":"Raja Ramesh"}
{"personId":115,"personName":"Raja Ramesh","gender":"male"}
Manisha Chand
Manisha Chand

Words That Decode Code

Updated on: 2025-06-05T10:58:46+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements