Java JsonBackReference-class And Method Code Example


Here is an example of using the @JsonBackReference annotation from the com.fasterxml.jackson.annotation package in the Jackson JSON library to handle bidirectional relationships during serialization and deserialization:

import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonManagedReference;

public class Parent {
    private String name;
    @JsonManagedReference
    private Child child;

    public Parent(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Child getChild() {
        return child;
    }

    public void setChild(Child child) {
        this.child = child;
    }
}

public class Child {
    private String name;
    @JsonBackReference
    private Parent parent;

    public Child(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Parent getParent() {
        return parent;
    }

    public void setParent(Parent parent) {
        this.parent = parent;
    }
}

In this example, the Parent class has a bidirectional relationship with the Child class. The Parent class has a child field that is annotated with @JsonManagedReference, and the Child class has a parent field that is annotated with @JsonBackReference. The @JsonManagedReference annotation indicates that the child field should be serialized normally, while the @JsonBackReference annotation indicates that the parent field should not be serialized.

Here is how you can use the above class

import com.fasterxml.jackson.databind.ObjectMapper;

public class Main {
    public static void main(String[] args) throws Exception {
        Parent parent = new Parent("parentName");
        Child child = new Child("childName");
        parent.setChild(child);
        child.setParent(parent);
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(parent);
        System.out.println(json);
    }
}

In this example, the Parent object is serialized to a JSON string using the ObjectMapper class. Because of the @JsonManagedReference annotation, the child field is serialized normally, but because of the @JsonBackReference annotation, the parent field is not serialized.

Note that this setup allows to avoid infinite loops when serializing and deserializing bidirectional relationships, because JsonBackReference tells Jackson to not serialize the back reference and JsonManagedReference tells Jackson to serialize the forward reference.