使用Spring MVC 开发 RESTful API(@JsonView的使用)

使用Spring MVC 开发 RESTful API(@JsonView的使用)

@JsonView使用步骤

1.使用接口来声明多个视图

举个例子,在User这个dto模型类中指定如下两个接口

2.在值对象的get方法上指定视图

3.在Controller方法上指定视图

前面三步弄完,我弄个测试类来测试一下

@Test

publicvoidwhenQuerySuccess()throwsException{

Stringresult=mockMvc.perform(MockMvcRequestBuilders.get("/user")

.param("userName","wjc")

.param("age","15")

.contentType(MediaType.APPLICATION_JSON_UTF8))

.andExpect(MockMvcResultMatchers.status().isOk())

.andExpect(MockMvcResultMatchers.jsonPath("$.length()").value(3))

.andReturn().getResponse().getContentAsString();

System.out.println(result);

}

@Test

publicvoidwhenGenInfoSuccess()throwsException{

Stringresult=mockMvc.perform(MockMvcRequestBuilders.get("/user/1")

.contentType(MediaType.APPLICATION_JSON_UTF8))

.andExpect(MockMvcResultMatchers.status().isOk())

.andExpect(MockMvcResultMatchers.jsonPath("$.userName").value("wjc"))

.andReturn().getResponse().getContentAsString();

System.out.println(result);

   }

测试结果

测试结果,测试成功

你可能感兴趣的:(使用Spring MVC 开发 RESTful API(@JsonView的使用))