@JsonView注解的使用

2,329 阅读1分钟

@JsonView

@JsonView可以过滤pojo的属性,使Controller在返回json时候,pojo某些属性不返回,比如User的密码,一般是不返回的,就可以使用这个注解

使用步骤

  • 使用接口来声明多个接口
  • 在值对象的get方法上指定视图
  • 在Controller方法上指定视图

示例:一个返回密码,一个不返回密码

public class Student implements Serializable {

    public interface simpleView {
    };

    public interface detailView extends simpleView {
    };

    private String username;
    private String password;

    @JsonView(simpleView.class)
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @JsonView(detailView.class)
    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

// controller层
@GetMapping("/student")
@JsonView(Student.simpleView.class)
public List<Student> getStudents() {
    List<Student> students = new ArrayList<>();
    students.add(new Student());
    students.add(new Student());
    return students;
}

@GetMapping("/student2")
@JsonView(Student.detailView.class)
public List<Student> getStudents2() {
    List<Student> students = new ArrayList<>();
    students.add(new Student());
    students.add(new Student());
    return students;
}

测试用例

@Autowired
private WebApplicationContext wac;

private MockMvc mockMvc;

@Before
public void setup() {
    mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}

@Test
// 简单视图不返回密码
public void testQuery() throws Exception {
    String contentAsString = mockMvc.perform(MockMvcRequestBuilders.get("/student"))
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andReturn().getResponse().getContentAsString();
    System.out.println(contentAsString);
}

@Test
// 详细视图返回密码
public void testQuery1() throws Exception {
    String contentAsString = mockMvc.perform(MockMvcRequestBuilders.get("/student2"))
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andReturn().getResponse().getContentAsString();
    System.out.println(contentAsString);
}