Jackson and JSON in Java, finally learn with a coding-first approach:
>> Download the eBookMocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.
Get started with mocking and improve your application tests using our Mockito guide:
Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.
Get started with understanding multi-threaded applications with our Java Concurrency guide:
Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:
Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.
But these can also be overused and fall into some common pitfalls.
To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:
Get started with Spring and Spring Boot, through the Learn Spring course:
>> LEARN SPRINGExplore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:
Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.
I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.
You can explore the course here:
Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.
Get started with Spring Data JPA through the guided reference course:
Refactor Java code safely β and automatically β with OpenRewrite.
Refactoring big codebases by hand is slow, risky, and easy to put off. Thatβs where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.
Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions β one for newcomers and one for experienced users. Youβll see how recipes work, how to apply them across projects, and how to modernize code with confidence.
Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.
1. Overview
In this tutorial, weβll examine the best ways to deal with bidirectional relationships in Jackson.
First, weβll discuss the Jackson JSON infinite recursion problem. Then weβll see how to serialize entities with bidirectional relationships. Finally, weβll deserialize them.
2. Infinite Recursion
Letβs take a look at the Jackson infinite recursion problem. In the following example, we have two entities, βUserβ and βItem,β with a simple one-to-many relationship:
The βUserβ entity:
public class User {
public int id;
public String name;
public List<Item> userItems;
}
The βItemβ entity:
public class Item {
public int id;
public String itemName;
public User owner;
}
When we try to serialize an instance of βItem,β Jackson will throw a JsonMappingException exception:
@Test(expected = JsonMappingException.class)
public void givenBidirectionRelation_whenSerializing_thenException()
throws JsonProcessingException {
User user = new User(1, "John");
Item item = new Item(2, "book", user);
user.addItem(item);
new ObjectMapper().writeValueAsString(item);
}
The full exception is:
com.fasterxml.jackson.databind.JsonMappingException:
Infinite recursion (StackOverflowError)
(through reference chain:
org.baeldung.jackson.bidirection.Item["owner"]
->org.baeldung.jackson.bidirection.User["userItems"]
->java.util.ArrayList[0]
->org.baeldung.jackson.bidirection.Item["owner"]
->β¦..
Weβll see over the course of the next few sections how to solve this problem.
3. Use @JsonManagedReference, @JsonBackReference
First, letβs annotate the relationship with @JsonManagedReference, and @JsonBackReference to allow Jackson to better handle the relation:
Hereβs the βUserβ entity:
public class User {
public int id;
public String name;
@JsonManagedReference
public List<Item> userItems;
}
And the βItemβ:
public class Item {
public int id;
public String itemName;
@JsonBackReference
public User owner;
}
Now letβs test out the new entities:
@Test
public void givenBidirectionRelation_whenUsingJacksonReferenceAnnotationWithSerialization_thenCorrect() throws JsonProcessingException {
final User user = new User(1, "John");
final Item item = new Item(2, "book", user);
user.addItem(item);
final String itemJson = new ObjectMapper().writeValueAsString(item);
final String userJson = new ObjectMapper().writeValueAsString(user);
assertThat(itemJson, containsString("book"));
assertThat(itemJson, not(containsString("John")));
assertThat(userJson, containsString("John"));
assertThat(userJson, containsString("userItems"));
assertThat(userJson, containsString("book"));
}
Hereβs the output of serializing the Item object:
{
"id":2,
"itemName":"book"
}
And hereβs the output of serializing the User object:
{
"id":1,
"name":"John",
"userItems":[{
"id":2,
"itemName":"book"}]
}
Note that:
- @JsonManagedReference is the forward part of reference, the one that gets serialized normally.
- @JsonBackReference is the back part of reference; itβll be omitted from serialization.
- The serialized Item object doesnβt contain a reference to the User object.
Also note that we canβt switch around the annotations. The following will work for the serialization:
@JsonBackReference
public List<Item> userItems;
@JsonManagedReference
public User owner;
But when we attempt to deserialize the object, itβll throw an exception, as @JsonBackReference canβt be used on a collection.
If we want to have the serialized Item object contain a reference to the User, we need to use @JsonIdentityInfo. Weβll look at this in the next section.
4. Use @JsonIdentityInfo
Now, letβs learn how we can help with the serialization of entities with bidirectional relationships using @JsonIdentityInfo.
Weβll add the class-level annotation to our βUserβ entity:
@JsonIdentityInfo(
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "id")
public class User { ... }
And to the βItemβ entity:
@JsonIdentityInfo(
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "id")
public class Item { ... }
Time for the test:
@Test
public void givenBidirectionRelation_whenUsingJsonIdentityInfo_thenCorrect()
throws JsonProcessingException {
User user = new User(1, "John");
Item item = new Item(2, "book", user);
user.addItem(item);
String result = new ObjectMapper().writeValueAsString(item);
assertThat(result, containsString("book"));
assertThat(result, containsString("John"));
assertThat(result, containsString("userItems"));
}
Hereβs the output of serialization:
{
"id":2,
"itemName":"book",
"owner":
{
"id":1,
"name":"John",
"userItems":[2]
}
}
5. Use @JsonIgnore
Alternatively, we can use the @JsonIgnore annotation to simply ignore one of the sides of the relationship, thus breaking the chain.
In the following example, weβll prevent the infinite recursion by ignoring the βUserβ property βuserItemsβ from serialization:
Hereβs the βUserβ entity:
public class User {
public int id;
public String name;
@JsonIgnore
public List<Item> userItems;
}
And hereβs our test:
@Test
public void givenBidirectionRelation_whenUsingJsonIgnore_thenCorrect()
throws JsonProcessingException {
User user = new User(1, "John");
Item item = new Item(2, "book", user);
user.addItem(item);
String result = new ObjectMapper().writeValueAsString(item);
assertThat(result, containsString("book"));
assertThat(result, containsString("John"));
assertThat(result, not(containsString("userItems")));
}
Finally, hereβs the output of serialization:
{
"id":2,
"itemName":"book",
"owner":
{
"id":1,
"name":"John"
}
}
6. Use @JsonView
We can also use the newer @JsonView annotation to exclude one side of the relationship.
In the following example, weβll use two JSON Views, Public and Internal, where Internal extends Public:
public class Views {
public static class Public {}
public static class Internal extends Public {}
}
Weβll include all User and Item fields in the Public View except the User field userItems, which will be included in the Internal View:
Hereβs our βUserβ entity:
public class User {
@JsonView(Views.Public.class)
public int id;
@JsonView(Views.Public.class)
public String name;
@JsonView(Views.Internal.class)
public List<Item> userItems;
}
And hereβs our βItemβ entity:
public class Item {
@JsonView(Views.Public.class)
public int id;
@JsonView(Views.Public.class)
public String itemName;
@JsonView(Views.Public.class)
public User owner;
}
When we serialize using the Public view, it works correctly because we excluded userItems from being serialized:
@Test
public void givenBidirectionRelation_whenUsingPublicJsonView_thenCorrect()
throws JsonProcessingException {
User user = new User(1, "John");
Item item = new Item(2, "book", user);
user.addItem(item);
String result = new ObjectMapper().writerWithView(Views.Public.class)
.writeValueAsString(item);
assertThat(result, containsString("book"));
assertThat(result, containsString("John"));
assertThat(result, not(containsString("userItems")));
}
But if we serialize using an Internal view, JsonMappingException is thrown because all the fields are included:
@Test(expected = JsonMappingException.class)
public void givenBidirectionRelation_whenUsingInternalJsonView_thenException()
throws JsonProcessingException {
User user = new User(1, "John");
Item item = new Item(2, "book", user);
user.addItem(item);
new ObjectMapper()
.writerWithView(Views.Internal.class)
.writeValueAsString(item);
}
7. Use a Custom Serializer
Next, weβll see how to serialize entities with bidirectional relationships using a custom serializer.
In the following example, weβll use a custom serializer to serialize the βUserβ property βuserItemsβ.
Hereβs the βUserβ entity:
public class User {
public int id;
public String name;
@JsonSerialize(using = CustomListSerializer.class)
public List<Item> userItems;
}
And hereβs the βCustomListSerializerβ:
public class CustomListSerializer extends StdSerializer<List<Item>>{
public CustomListSerializer() {
this(null);
}
public CustomListSerializer(Class<List> t) {
super(t);
}
@Override
public void serialize(
List<Item> items,
JsonGenerator generator,
SerializerProvider provider)
throws IOException, JsonProcessingException {
List<Integer> ids = new ArrayList<>();
for (Item item : items) {
ids.add(item.id);
}
generator.writeObject(ids);
}
}
Now, letβs test out the serializer. As we can see, the right kind of output is being produced:
@Test
public void givenBidirectionRelation_whenUsingCustomSerializer_thenCorrect()
throws JsonProcessingException {
User user = new User(1, "John");
Item item = new Item(2, "book", user);
user.addItem(item);
String result = new ObjectMapper().writeValueAsString(item);
assertThat(result, containsString("book"));
assertThat(result, containsString("John"));
assertThat(result, containsString("userItems"));
}
Hereβs the final output of the serialization with the custom serializer:
{
"id":2,
"itemName":"book",
"owner":
{
"id":1,
"name":"John",
"userItems":[2]
}
}
8. Deserialize With @JsonIdentityInfo
Now, letβs see how to deserialize entities with bidirectional relationships using @JsonIdentityInfo.
Hereβs the βUserβ entity:
@JsonIdentityInfo(
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "id")
public class User { ... }
And the βItemβ entity:
@JsonIdentityInfo(
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "id")
public class Item { ... }
Weβll write a quick test, starting with some manual JSON data we want to parse, and finishing with the correctly constructed entity:
@Test
public void givenBidirectionRelation_whenDeserializingWithIdentity_thenCorrect()
throws JsonProcessingException, IOException {
String json =
"{\"id\":2,\"itemName\":\"book\",\"owner\":{\"id\":1,\"name\":\"John\",\"userItems\":[2]}}";
ItemWithIdentity item
= new ObjectMapper().readerFor(ItemWithIdentity.class).readValue(json);
assertEquals(2, item.id);
assertEquals("book", item.itemName);
assertEquals("John", item.owner.name);
}
9. Use Custom Deserializer
Finally, letβs deserialize the entities with a bidirectional relationship using a custom deserializer.
In the following example, weβll use a custom deserializer to parse the βUserβ property βuserItemsβ.
Hereβs the βUserβ entity:
public class User {
public int id;
public String name;
@JsonDeserialize(using = CustomListDeserializer.class)
public List<Item> userItems;
}
And hereβs our βCustomListDeserializerβ:
public class CustomListDeserializer extends StdDeserializer<List<Item>>{
public CustomListDeserializer() {
this(null);
}
public CustomListDeserializer(Class<?> vc) {
super(vc);
}
@Override
public List<Item> deserialize(
JsonParser jsonparser,
DeserializationContext context)
throws IOException, JsonProcessingException {
return new ArrayList<>();
}
}
Finally, hereβs the simple test:
@Test
public void givenBidirectionRelation_whenUsingCustomDeserializer_thenCorrect()
throws JsonProcessingException, IOException {
String json =
"{\"id\":2,\"itemName\":\"book\",\"owner\":{\"id\":1,\"name\":\"John\",\"userItems\":[2]}}";
Item item = new ObjectMapper().readerFor(Item.class).readValue(json);
assertEquals(2, item.id);
assertEquals("book", item.itemName);
assertEquals("John", item.owner.name);
}
10. Resolving Jackson Exception
When we use multiple bidirectional relationships in the same entity, we might encounter an exception during serialization:
com.fasterxml.jackson.databind.JsonMappingException: Multiple back-reference properties with name 'defaultReference'
This happens because Jackson assigns the default reference name βdefaultReferenceβ to every @JsonBackReference unless we explicitly provide a value. If an entity has more than one back-reference without specifying a unique name, Jackson doesnβt know how to distinguish them.
Suppose we have a User with two lists of items: wishlist and soldItems. Both reference the User as the owner:
public class User {
public int id;
public String name;
@JsonManagedReference
public List wishlist = new ArrayList<>();
@JsonManagedReference
public List soldItems = new ArrayList<>();
}
public class Item {
public int id;
public String itemName;
@JsonBackReference
public User owner;
}
This will cause Jackson to throw a JsonMappingException during serialization because it cannot distinguish between multiple back-references that share the same default name.
To resolve this, we need to give each pair of references a unique name via the value attribute:
public class User {
public int id;
public String name;
@JsonManagedReference(value="wishlistRef")
public List wishlist = new ArrayList<>();
@JsonManagedReference(value="soldItemsRef")
public List soldItems = new ArrayList<>();
}
public class Item {
public int id;
public String itemName;
@JsonBackReference(value="wishlistRef")
public User wishlistOwner;
@JsonBackReference(value="soldItemsRef")
public User soldOwner;
}
Now, Jackson knows exactly which back-reference corresponds to which managed reference, and serialization works correctly.
We can write a test example to demonstrate how using named @JsonManagedReference and @JsonBackReference annotations allows Jackson to correctly serialize objects with multiple back-references without throwing an exception:
@Test
public void givenMultipleBackReferencesOnWishlist_whenNamedReference_thenNoException() throws JsonProcessingException {
User user = new User();
user.id = 1;
user.name = "Alice";
Item item1 = new Item();
item1.id = 101;
item1.itemName = "Book";
item1.wishlistOwner = user;
Item item2 = new Item();
item2.id = 102;
item2.itemName = "Pen";
item2.wishlistOwner = user;
user.wishlist = List.of(item1, item2);
Item item3 = new Item();
item3.id = 201;
item3.itemName = "Laptop";
item3.soldOwner = user;
Item item4 = new Item();
item4.id = 202;
item4.itemName = "Phone";
item4.soldOwner = user;
user.soldItems = List.of(item3, item4);
String json = new ObjectMapper().writeValueAsString(user);
assertThat(json, containsString("Alice"));
assertThat(json, containsString("Book"));
assertThat(json, containsString("Pen"));
}
11. Conclusion
In this article, we illustrated how to serialize/deserialize entities with bidirectional relationships using Jackson.
