Java ReadableObjectId-class And Method Code Example


Here is an example of how to use the ReadableObjectId 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.ObjectIdGenerators;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.deser.ValueInstantiator;
import com.fasterxml.jackson.databind.deser.std.StdValueInstantiator;
import com.fasterxml.jackson.databind.deser.std.StdValueInstantiator.ReadableObjectId;

@JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, property = "@id")
public class Example {
    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        String json = "{\"@id\":1,\"name\":\"Parent\",\"child\":{\"@id\":2,\"name\":\"Child\",\"parent\":1}}";
        Parent parent = mapper.readValue(json, Parent.class);
        System.out.println(parent.toString());
    }

    static class Parent {
        private String name;
        private Child child;

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

        @Override
        public String toString() {
            return "Parent{" +
                    "name='" + name + ''' +
                    ", child=" + child +
                    '}';
        }
    }

    static class Child {
        private String name;
        private Parent parent;

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

        @Override
        public String toString() {
            return "Child{" +
                    "name='" + name + ''' +
                    ", parent=" + parent +
                    '}';
        }
    }
}

This code creates an instance of the ObjectMapper class, deserialize a json string to Parent class, which has a circular reference to Child class, and use JsonIdentityInfo annotation to handle the circular references by using a sequence generator for object ids. Finally it prints the resulting object to the console.