DarkChipolata
DarkChipolata

Reputation: 965

JSON serialization of an object tree structure

When serializing my POJOs with relationships, I used to create different views for each of my classes. For every class, I created a view Basic, displaying only scalar properties, and Detail including in top of that all my relationships. It looks like this :

public class Stage extends BasicDomainObject {

    @JsonView(Views.Stage.Basics.class)
    protected String stageType = "";

    @JsonView(Views.Stage.Basics.class)
    protected String scheduledReleaseGraph = "";

    @JsonView(Views.Stage.Details.class)
    private Pipeline pipeline;

    // ...
}

Then, in my REST api layer, I could serialize the correct view by specifying the right one:

mapper.writerWithView(Views.Stage.Details.class).writeValueAsString(bean);

Now, I had to add a field private Stage parentStage in my Stage class. I'm trying to have an output looking like this with my Details view :

{
    "id": 2,
    "type": "dev",
    "scheduledReleaseGraph" "xxx",
    "pipeline" : {
         ...
    },
    "parent" : {
        "id": 1,
        "type": "dev",
        "scheduledReleaseGraph" "yyy"
    }
}

The goal here is to display the parent association with only one level of depth. What is the common pattern to achieve this ?

Upvotes: 0

Views: 699

Answers (1)

Mathias G.
Mathias G.

Reputation: 5085

If you use Jackson 2.0, I would look into the JsonIdentityInfo attribute: https://fasterxml.github.io/jackson-annotations/javadoc/2.0.0/com/fasterxml/jackson/annotation/JsonIdentityInfo.html

This annotation helps you to handle cyclic references when serializing/deserializing.

Upvotes: 1

Related Questions