0

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 ?

DarkChipolata
  • 925
  • 1
  • 10
  • 29

1 Answers1

1

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.

Mathias G.
  • 4,875
  • 3
  • 39
  • 60
  • From what I understood, JsonIdentityInfo let Jackson know about the identity of a given object. I don't want to prevent cyclic references, I want to limit the depth of me tree to exactly 1 nesting level. – DarkChipolata Dec 20 '17 at 15:22
  • Maybe this can help you? https://stackoverflow.com/questions/21788434/how-to-serialize-nested-objects-limiting-depth-of-serialization – Mathias G. Dec 20 '17 at 15:29
  • Already seen that answer, but it doesn't fit my needs. My POJO can be proxied by a lazy loading mechanism, and I have no control on whether it can be dynamically enabled for a given property. Therefore, even be setting `parentStage.parentStage` to `null` when serializing, Jackson still calls `getParentStage` and triggers lazy loading. Moreover, custom serializers seems like total overkill and would need an implementation for each class of this kind. Do I have any other options ? – DarkChipolata Dec 21 '17 at 08:57