Jackson JSON serialization, recursion avoidance by level defining

前端 未结 7 1299
庸人自扰
庸人自扰 2020-12-02 20:46

I use Jackson library for serialization of my pojo objects into JSON representation. For example I have class A and class B:

class A {
  privat         


        
相关标签:
7条回答
  • 2020-12-02 21:15

    After several months and a lot of research, I've implemented my own solution to keep my domain clear of jackson dependencies.

    public class Parent {
        private Child child;
        public Child getChild(){return child;} 
        public void setChild(Child child){this.child=child;}
    }
    
    public class Child {
        private Parent parent;
        public Child getParent(){return parent;} 
        public void setParent(Parent parent){this.parent=parent;}
    }
    

    First, you have to declare each of your entities of the bidirectional relationship in something like this:

    public interface BidirectionalDefinition {
    
        @JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id", scope=Parent.class)
        public interface ParentDef{};
    
        @JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id", scope=Child.class)
        public interface ChildDef{};
    
    }
    

    After that, the object mapper can be automatically configured:

    ObjectMapper om = new ObjectMapper();
    Class<?>[] definitions = BidirectionalDefinition.class.getDeclaredClasses();
    for (Class<?> definition : definitions) {
        om.addMixInAnnotations(definition.getAnnotation(JsonIdentityInfo.class).scope(), definition);
    }
    
    0 讨论(0)
提交回复
热议问题