How to use @JsonIdentityInfo with circular references?

戏子无情 提交于 2019-11-27 13:47:44

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.

There are several approaches to solve this circular references or infinite recursion issues. This link explain in details each one. I have solved my issues including @JsonIdentityInfo annotation above each related entity, although @JsonView is more recent and may it's a better solution depending of your scenery.

@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")

Or using an IntSequenceGenerator implementation:

@JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class)
@Entity
public class A implements Serializable 
...

In some cases, it can be necessary to annotate the Id Property with @JsonProperty("id")

For example, in my case, this made my application run correctly.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!