Importance of @JsonView annotation using Jackson in Java?


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

Syntax

@Target(value={ANNOTATION_TYPE,METHOD,FIELD})
@Retention(value=RUNTIME)
public @interface JsonView

Example

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"}
raja
Published on 06-Nov-2019 14:19:01
Advertisements