spring-bootjacksonjson-view

JsonView ignore all but annotated properties


I have the following JsonView configuration:

public class JsonViews {

    public static class AdminView {
    }

    public static class PublicView extends AdminView {
    }
}

I have the following entity:

public class UserEntity {

    @JsonView(JsonViews.AdminView.class)
    private int id;

    @JsonView(JsonViews.PublicView.class)
    private int name;

    // getters / setters
}

In my controller I have the following methods:

Possible? If not, is there another solution?


Solution

  • It is possible if you have just a single view for the name-only case;

    public class JsonViews {
    
        public static class NameView {
        }
    }
    

    and the entity;

    public class UserEntity {
    
        private int id;
    
        @JsonView(JsonViews.NameView.class)
        private int name;
    
        // getters / setters
    }
    

    and controller methods;

    @JsonView(JsonViews.NameView.class)
    @RequestMapping("/admin/users")
    public List<User> getUsersWithOnlyName() {
        return userGetter.getUsers();
    }
    

    will get you only name field for every User, and

    @RequestMapping("/users")
    public List<User> getUsers() {
        return userGetter.getUsers();
    }
    

    will get you the whole entity, the default behaviour.


    More on @JsonView on Spring here under topic 6. Using JSON Views with Spring, also on spring.io