Jackson json two way object reference

后端 未结 1 1401
攒了一身酷
攒了一身酷 2020-12-18 12:30

I have a pair of objects like

public class Obj1 {
    public int id;
    public String name;
    public Obj2 obj2;
}

public class Obj2 {
    public int id;
         


        
相关标签:
1条回答
  • 2020-12-18 13:27

    You are looking at @JsonIgnoreProperties, it will give what is needed and avoid json recursion.

    public class Obj1 {
        public int id;
        public String name;
        @JsonIgnoreProperties("obj1list")
        public Obj2 obj2;
    }
    
    public class Obj2 {
        public int id;
        public String name;
        @JsonIgnoreProperties("obj2")
        public List<Obj1> obj1list;
    }
    


    UPDATE

    I always perfers @JsonIgnoreProperties over JsonBackReference and JsonManagedReference. As it not only does the trick, but also not escapes any data serialization (which is the case required here).

    I also have a sample project on github deals with this situation. Look for entity class codes School.java & District.java. Its an mvn spring-boot executable code, if you wanna run a test.

    From Javadoc, starting with Jackson 2.0, @JsonIgnoreProperties annotation can be applied both to classes and to properties. If used for both, actual set will be union of all ignorals: that is, you can only add properties to ignore, not remove or override. So you can not remove properties to ignore using per-property annotation.


    HOW IT WORKS

    When you define @JsonIgnoreProperties at propety level, while serialization/deserization it will work on the refered property object.

    So here, when Obj1 is being parsed, you asked parser to ignore obj1list property of obj2. And similary, while parsing Obj2 it will ignore contained obj2 references in the Obj collection. So your parsing will look like below:

    Obj1 : {
        id : int,
        name : string,
        Obj2 : {
         id : int,
         name : string
         obj1list : //ignored avoids recursion
        }
    }
    
    Obj2 : {
        id : int,
        name : string,
        obj1list : [{
         id : int,
         name : string,
         obj2 : //ignored avoids recursion
        },
        {
         id : int,
         name : string
         obj2 : //ignored avoids recursion
        }
        ]
    }
    
    0 讨论(0)
提交回复
热议问题