Search code examples
javajsonjacksonjson-view

Can I serialize a property using a Jackson @JsonView?


I have a complicated class in my REST API:

class Complicated {
    String foo
    Integer bar
    Instant baz
    ...
    // lots more
}

I also have another class that contains a collection of Complicated:

class HasComplications {
    String description

    List<Complicated> complications
}

When I serialize my HasComplications (with Spring MVC), I only want a snippet of each Complicated:

{
    description: "hello world",
    complications: [ {
      foo: "foo1",
      bar: 42
    ] }
}

When I'm directly serializing a Complicated, I can use @JsonView to tell Jackson which set of properties to serialize:

class Complicated {
    @JsonView(Views.Snippet) String foo
    @JsonView(Views.Snippet) Integer bar
    Instant baz
    ...
    // lots more
}

However, when I serialize Complicated transitively in the complications property, Jackson serializes all of the properties. Is there a way for me to declaratively tell it "use this view when serializing this property"?

class HasComplications {
    String description

    @UseJsonView(Views.Snippet)
    List<Complicated> complications
}

Solution

  • There is no such functionality currently.

    One thing you can do is to use @JsonIgnoreProperties on property. However, I think that would only work for POJO values and not to contents of Lists or Maps so that does not help you here. Filing an issue to make this work for structured types might make sense.