Technology: Jackson-databind is one of the libraries widely used in modern spring-based applications for serialization or deserialization from/to JSON. Jackson library will convert the object to JSON, and vice versa.
If the object is complex and needs to customize the serialization/ deserialization then we need to write Custom Serializer which extends default Jackson provided serializer i.e. com.fasterxml.jackson.databind.ser.std.StdSerializer.
Defining Custom Serializer: We will create StudentCustomSerializer class to customize the Student class, it must extend.
com.fasterxml.jackson.databind.ser.std.StdSerializer and create required constructor methods and default constructor with no-arguments.
We need to implement one abstract serialize method, how to want to serialize the object.
And Student class look like below:
Here we are criticizing the student class with the sonJsonSerialize annotation and passing the above custom serializer class to use the attribute so that it will be called during the serializing.
If we run and our main class will look like below:
If we run the program output will look like below:
Create course POJO type class and add the List in student class.
Create student variables in Courses class, so that it will maintain one-to-many relations.
If we serialize the student class using object mapper, as a student depends on Course, Course will depend on Student Serialization. We can observe a cycle, java will throw StackOverflow exception, and to overcome this circular Reference, Jackson library provides new annotation @JsonIdentityInfo.
Add the below line at the class level of the student so that from the 2nd time onwards it will serialize the only id property instead of the whole object.
After adding student class look like below:
main class :
If we run without @JsonIdentityInfo annotation, we can observe the below error in the console.
If we run with annotation, we can see the serialized student output:
Now we can observe course class will only contain student IDs, other fields are skipped.
Custom Serializer AutoWired Problem:
If we would like @autowired some of the bean into our custom serializer, by default not possible, as the custom serializer is not of spring bean type.
ObjectMapper provides one to way injects using objectInstantiator, spring extends this objectInstantiator to autowire the beans inside the custom serializer class using the below code.
ObjectMapper mapper = Jackson2ObjectMapperBuilder.json().build();
This we can inject spring beans into a custom serializer, and we can override the serialize according to our needs.
Conclusion: Jackson is one of the libraries to used serializes the object from/to JSON in Java application development, it provides a useful annotation to avoid Circular reference.
Jackson library also provides the way to customize the serialization, and also we saw how to inject spring beans into a custom serializer using HandlerInstantiator.