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?

4

1 回答 1

1

如果您对仅名称案例只有一个视图,则可能是这样;

public class JsonViews {

    public static class NameView {
    }
}

及该实体;

public class UserEntity {

    private int id;

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

    // getters / setters
}

和控制器方法;

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

将为您提供每个名称字段User,并且

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

将为您提供整个实体,即默认行为。


更多关于@JsonView这里Spring 主题6. Using JSON Views with Spring,也在spring.io

于 2019-08-01T06:07:37.320 回答