4

I have the following class I want to serialize.

class User {

    private String username;
    @JsonView(Views.Default.class)
    private List<User> followers;
}

The views are defined as follows:

class Views {
    static class Default { }
    static class Follower { } 
}

The idea is to fetch a user and show a list of followers (User type) but without the followersfield.

{
  "username": "aaaaa",
  "followers": [
    { "username" : "bbbbb" },
    { "username" : "ccccc" }
  ]
}

What's the best way to tell Jackson to apply the Follower view on the followers property when serializing a User object?

With the current configuration I still see the followers property in array of users.

Thanks.

Matteo Pacini
  • 21,796
  • 7
  • 67
  • 74
  • What does it means without followers property? Do you want return just json array as response? – eg04lt3r Oct 06 '16 at 22:02
  • @eg04lt3r It means that the user objects in the `followers` must be deserialised using `Views.Followers.class` view. `followers` property will be visible on the outer object, but not in the inner ones. – Matteo Pacini Oct 06 '16 at 22:04
  • If I understood correctly you want hide followers property in children collection of user when serialize, right? – eg04lt3r Oct 06 '16 at 22:19
  • @eg04lt3r exactly! – Matteo Pacini Oct 06 '16 at 22:20
  • I think you should use some kind of filter for this purpose, please check this link https://codedump.io/share/kDsdkw2CeMNV/1/how-to-filter-properties-on-a-self-reference-using-jackson. It may help you, I suppose there is no way to figure out this without filter. – eg04lt3r Oct 07 '16 at 00:02
  • When you serialize user object you should say to mapper that we want ignore this collection for child objects and this can be done with filter. Also this link may be helpful for you: http://stackoverflow.com/questions/12676249/how-do-i-serialize-an-associated-object-differently-using-jackson-and-annotation?rq=1 – eg04lt3r Oct 07 '16 at 00:04

1 Answers1

1

You will need to use ObjectWriter instead of ObjectMapper to specify active view to use for serialization. So, for example:

String json = mapper.writerWithView(Views.Compact.class)
   .writeValueAsJson(user);

since you will need to use view other than Default (or its sub-classes): views are used for inclusion.

StaxMan
  • 113,358
  • 34
  • 211
  • 239