How to use @JsonIdentityInfo with circular references?

后端 未结 3 1933
小鲜肉
小鲜肉 2020-12-03 05:47

I am trying to use the @JsonIdentityInfo from Jackson 2 as described here.

For testing purposes I created the following two classes:

public class A
{         


        
3条回答
  •  甜味超标
    2020-12-03 06:25

    It seems jackson-jr has a subset of Jackson's features. @JsonIdentityInfo must not have made the cut.

    If you can use the full Jackson library, just use a standard ObjectMapper with the @JsonIdentityInfo annotation you suggested in your question and serialize your object. For example

    @JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="@id")
    public class A {/* all that good stuff */}
    
    @JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="@id")
    public class B {/* all that good stuff */}
    

    and then

    A a = new A();
    B b = new B(a);
    a.setB(b);
    ObjectMapper mapper = new ObjectMapper();
    System.out.println(mapper.writeValueAsString(a));
    

    will generate

    {
        "@id": 1,
        "b": {
            "@id": 2,
            "a": 1
        }
    }
    

    where the nested a is referring to the root object by its @id.

提交回复
热议问题