Jackson JSON Views
JSON Views is another important element of Jackson. JSON Views is also used for serializing and deserializing Java objects. We use @JsonView annotation for customizing the view at the time of serializing/deserializing.
In this section, we will understand how we can perform serialization/deserialization using JSON Views and how we can customize the view.
Serialize Using JSON Views
In order to serialize an object by using @JsonView, we first create a view, and then we will use it for serialization. Let’s take an example to understand how we can use JSON View to serialize an object.
JSONViewExample1.java
Output:
By using multiple JSON Views, we can also serialize an object in Java. Here, we create a view where the Internal view extends to the Public one. So, the Views class looks like this:
We will modify the Student class. In the Student class, stdId and stdName fields will be included in the Public view. We create a new field, i.e., the course which will be included in the Internal view. So, our Student class looks like this:
Now, let’s take an example to understand how, we can serialize an object using multiple JSON Views:
JSONViewExample2.java
Output:
Deserialize using JSON Views
Just like serialization, we can also deserialize JSON strings into Java objects by using JSON Views. Let’s take an example to understand how deserialization is done by using JSON Views.
JSONViewExample3.java
Output:
Serialize using the customize JSON Views
We can also Java objects by using the customize JSON View. In order to serialize Java objects by using the customize JSON View, we first customize the JSON view by using BeanPropertyWriter. We create the 65UpperCasingWriter class by extending BeanPropertyWriter for transforming the student name to upper case.
Let’s create the UpperCasingWriter class for transforming the student name to upper case.
UpperCasingWriter.java
Now, we will create a custom modifier to set the student name BeanPropertyWriter with our CustomCasingWriter.
CustomBeanSerializerModifier.java
Let’s take an example to understand how serialization is done by using customize JSON View.
JSONViewExample4.java
Output: