Apply JsonView when serializing with Jackson

I have the following class that I want to serialize.

class User {

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

Views are defined as follows:

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

The idea is to select a user and show a list of subscribers (user type), but without a field followers.

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

What is the best way to tell Jackson to apply a view Followerto a property followerswhen serializing an object User?

In the current configuration, I still see the property followersin the users array.

Thank.

+4
source share
1 answer

You will need to use ObjectWriterinstead ObjectMapperto indicate the active view for serialization. So for example:

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

, Default ( ): .

+1

Source: https://habr.com/ru/post/1656993/


All Articles