Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use @JsonIdentityInfo with circular references?

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
{
    private B b;
    // constructor(s) and getter/setter omitted
}
public class B
{
    private A a;
    // see above
}

Of course, the naive approach failes:

@Test
public void testJacksonJr() throws Exception
{
    A a = new A();
    B b = new B(a);
    a.setB(b);
    String s = JSON.std.asString(a);// throws StackOverflowError
    Assert.assertEquals("{\"@id\":1,\"b\":{\"@id\":2,\"a\":1}}", s);
}

Adding @JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="@id") to class A and/or class B does not work either.

I was hoping that I could serialize (and later deserialize) a to something like this: (not too sure about the JSON though)

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

How can I do that?

like image 640
Burkhard Avatar asked May 18 '16 14:05

Burkhard


2 Answers

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 
...
like image 132
Cassio Seffrin Avatar answered Nov 17 '22 06:11

Cassio Seffrin


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.

like image 21
Sotirios Delimanolis Avatar answered Nov 17 '22 05:11

Sotirios Delimanolis