1

我有这种情况:

public class Project{

    private long id;

    private List<User> users;

    // other properties and getter setter etc
}

public class User{

   @JsonView(MinimalUser.class) 
   private long id;

   @JsonView(MinimalUser.class)
   private String name;

   private ComplexObject anything;

}

现在休息方法:


    @JsonView(MinimalUser.class)
    @GetMapping("/client/{id}")
    public List<Project> findProjectsByClientId(@PathVariable long id) {
        return projectService.findProjectsByClientId(id);
    }

在这里,我只想用最少的用户对象初始化一个项目,但是什么都不会被初始化,因为我的项目中没有“MinimalUser.class”JsonView,因此它没有被初始化。

我不想将@JsonView 注释放在项目中的所有变量中,因为这将是矫枉过正。

如何告诉控制器仅将 @JsonView-Filtering/Serialization 应用于项目的用户(子)?

因为这个调用工作正常(我只得到必填字段):


    @JsonView(MinimalUser.class)
    @GetMapping("/minimal")
    public List<User> findAllUsers() {
        return userService.findAllUsers();
    }

4

1 回答 1

2

如果您扩展MinimalUser视图并将这个新视图应用到整个项目,您可以获得以下结果:

public class MinimalProject extends MinimalUser {}
public class DetailedProject extends MinimalProject {}

// apply view to entire class
@JsonView(MinimalProject.class)
public class Project {
    // keep existing fields as is

    // limit view for project
    @JsonView(DetailedProject.class)
    private String details;
}

// test
ObjectMapper mapper = new ObjectMapper().disable(MapperFeature.DEFAULT_VIEW_INCLUSION);

User u = new User();
u.setId(1);
u.setName("John Doe");
u.setEmail("john@doe.com");
u.setDetails("some details");

System.out.println("user default view: " + mapper.writeValueAsString(u));

System.out.println("user minimal view: " + mapper.writerWithView(MinimalUser.class).writeValueAsString(u));

Project p = new Project();

p.setId(1000);
p.setName("MegaProject");
p.setUsers(Arrays.asList(u));
p.setDetails("Project details: worth $1M");

System.out.println("project default view: " + mapper.writeValueAsString(p));

System.out.println("project minimal view: " + mapper.writerWithView(MinimalProject.class).writeValueAsString(p));

输出

user default view: {"id":1,"name":"John Doe","details":"some details","email":"john@doe.com"}
user minimal view: {"id":1,"name":"John Doe"}
project default view: {"id":1000,"users":[{"id":1,"name":"John Doe","details":"some details","email":"john@doe.com"}],"name":"MegaProject","details":"Project details: worth $1M"}
project minimal view: {"id":1000,"users":[{"id":1,"name":"John Doe"}],"name":"MegaProject"}
于 2020-05-02T23:23:13.507 回答