Reputation: 22846
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 followers
field.
{
"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.
Upvotes: 4
Views: 332
Reputation: 116522
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.
Upvotes: 1