In recent times, I did a lot practise of micro-service with spring boot. And handled a lot of JSON(Jackson) related serialization and deserialization issues. In this post, I will share some tricky how to “fix” Circular References.
Note: What I want to do are:
- I can serialize object to JSON string
- I can deserialize the JSON string to the same object(at least all important info retains)
Let’s see a quick demo first: (
Book has its
Author keeps a list of his/her
Now, we can have a serialization sample as:
Then it will throw this exception:
Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion (StackOverflowError) (through reference chain: ...
JSON is pretty to hard to demonstrate the data with Circular References
Thx to Jackson, with @JsonIdentityInfo, we can easy fix this issue.
After I add
@JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="@id") to both class, then I can have the JSON string as:
However, I am not sure whether this JSON string can be deserialized by other libraries(e.g. GSON), or other languages, my guess is NOT.
Note: Think twice before using it!