Java ObjectIdReferenceProperty-class And Method Code Example


Here is an example of how to use the ObjectIdReferenceProperty class from the com.fasterxml.jackson.databind package in the Jackson library for Java:

import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonIdentityReference;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import com.fasterxml.jackson.databind.ObjectMapper;

@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public class Example {
    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        Parent parent = new Parent();
        parent.setId(1);
        parent.setName("Parent");
        Child child = new Child();
        child.setId(2);
        child.setName("Child");
        child.setParent(parent);
        parent.setChild(child);
        System.out.println(mapper.writeValueAsString(parent));
    }

    static class Parent {
        private int id;
        private String name;
        @JsonIdentityReference(alwaysAsId = true)
        private Child child;

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        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;
        }
    }

    static class Child {
        private int id;
        private String name;
        @JsonIdentityReference(alwaysAsId = true)
        private Parent parent;

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        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;
        }
    }
}

This code creates an instance of the ObjectMapper class and sets it to use ObjectIdReferenceProperty to handle circular references. It creates a Parent and Child object and sets their relationship to each other as circular. Finally it serializes an instance of the Parent class, and prints the resulting JSON string to the console.

The output of this code would be:

{"id":1,"name":"Parent","child":{"id":2,"name":"Child","parent":1}}

You can see the circular references are handled with the id value of the object.

Please note that, in this example, the JsonIdentityInfo and JsonIdentityReference annotations are used to configure the handling of circular references. They are necessary to use ObjectIdReferenceProperty class.