Search code examples
jacksonjsog

jsog-jackson: Serializing object graphs


I am trying to serialize an object graph with parent/child references, essentially I have an entity that looks like this:

@Entity (name = "Container")
@JsonIdentityInfo(generator=JSOGGenerator.class)
public class Container {
    public String type = "parent";

    @JsonManagedReference ("child")
    @OneToMany (mappedBy = "parent", cascade = CascadeType.PERSIST)
    public List<Child> children;
}

@Entity (name = "Child")
@JsonIdentityInfo(generator=JSOGGenerator.class)
public class Child {
    public String type = "child";

    @JsonBackReference ("child")
    @ManyToOne
    public Parent parent;
}

when I try to serialize this to the client, then this is what I get:

{
    "type": "parent",
    @id: 1
    "children": [
        {
            "type": "child",
            @id: 2
        },
        { ... }
    ]
}

I see @id properties on all objects but there is no sight of any @ref properties. If I have understood jsog and jsog-jackson right, then this is what should actually be serialized:

{
    "type": "parent",
    @id: 1
    "children": [
        {
            "type": "child",
            @id: 2
            @ref: 1
        },
        { ... }
    ]
}

What I would really like to have is a way of restoring the original back reference to the parent after restoring the serialized JSOG in the browser, so that instead of @ref I get the parent property in each child object back.


Solution

  • Your using two conflicting approaches to managing circular relationships. You can either use the JSOGGenerator OR the @JsonManagedReference and @JsonBackReference annotations.

    The JSOGGenerator will include the @id and @ref properties in the JSON serialized format which is useful for deserializing the object in another language such as JavaScript.

    The @JsonManagedReference and @JsonBackReference use the Java class information to identify the circular reference and subsequently that information is excluded from the JSON serialized format so another language like JavaScript can't deserialize the object because the required information is missing.

    Another benefit to the JSOGGenerator is that it can handle deeply nested circular relationships as opposed to a limited parent-child relationship.