1

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:

  • I want this method to return ALL properties

    @JsonView(JsonViews.AdminView.class)
    public List<User> getAllOnlyForAdmin { return foo; }
    
  • I want this to return ONLY the name property

    @JsonView(JsonViews.PublicView.class)
    public List<User> getAllOnlyForAdmin { return foo; }
    

Possible? If not, is there another solution?

buræquete
  • 14,226
  • 4
  • 44
  • 89
SexyMF
  • 10,657
  • 33
  • 102
  • 206

1 Answers1

1

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

buræquete
  • 14,226
  • 4
  • 44
  • 89