![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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"}
Advertisements