Technology: Jackson-databind is the one of the libraries widely used in modern spring-based applications for serialization or deserialization from/to JSON. Jackson library will convert object to JSON, and vice versa.
If the object is complex, and need 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 want to serialize the object.
And Student class look like below:
Here we are annotating the Student class with @JsonSerialize annotation and passing above custom Serializer class to using attribute, so that during the serializing it will be invoked.
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
Create student variable in Courses class, so that it will maintain one-to-many relation.
If we serialize the student class using objectmapper, as student is depends on Course, Course will depend on Student Serailization, we can observe a cycle, java will throw stackOverFlowException, to overcome this circular Reference, Jackson library provides new annotation @JsonIdentityInfo.
Add the below line at class level of the student so that from 2nd time onwards it will serialize the only id property instead of whole object.
After adding student class look like below:
main class :
If we run without @JsonIdentityInfo annotation, we can observer below error in console.
If we run with annotation, we can see the serialized student output:
Now we can observer course class will only contain student id, 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 custom serializer is not of spring bean type.
objectMapper provide one to way inject using objectInstantiator, spring extends this objectInstantiator to autowire the beans inside custom serializer class using below code.
ObjectMapper mapper = Jackson2ObjectMapperBuilder.json().build();
This we can inject spring beans into custom serializer, and we can override the serialize according to our needs.
Spring Custom Serializers with @JsonIdentityInfo - Enterprise Java Spring https://t.co/EihRmFh7ih— Java Code Geeks (@javacodegeeks) January 28, 2019
Conclusion: Jackson is one of the libraries to used serialize the object from/to JSON, it provides 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 custom serializer using HandlerInstantiator.