1.使用場(chǎng)景
在某一些請(qǐng)求返回的JSON中,我們并不希望返回某些字段。而在另一些請(qǐng)求中需要返回某些字段庐氮。
例:用戶(hù)對(duì)象
- 在
查詢(xún)列表
請(qǐng)求中膘茎,不返回password
字段 - 在
獲取用戶(hù)
詳情中,返回password
字段
2.實(shí)現(xiàn)
2.1 @JsonView
的使用步驟
- 1.使用接口來(lái)聲明多個(gè)視圖
- 2.在值對(duì)象的get方法上指定視圖
- 3.在Controller的方法上指定視圖
2.2 完整事例代碼
2.2.1User
對(duì)象定義
public class User{
/**
* 用戶(hù)簡(jiǎn)單視圖
*/
public interface UserSimpleView{};
/**
* 用戶(hù)詳情視圖
*/
public interface UserDetailView extends UserSimpleView{};
private String username;
private String password;
private String age;
@JsonView(UserSimpleView.class)
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@JsonView(UserDetailView.class)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@JsonView(UserSimpleView.class)
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
- 這里完成了步驟1和步驟2
- 定義了步驟1的兩個(gè)視圖接口
UserSimpleView
和UserDetailView
,UserDetailView
繼承UserSimpleView
脚草,UserDetailView
擁有視圖UserSimpleView
的屬性 - 完成了步驟2的在相應(yīng)的get方法上聲明JsonView
2.2.2 定義UserController
@RestController
public class UserController {
@GetMapping("/user")
@JsonView({User.UserSimpleView.class})
public List<User> query(UserQueryCondition userQueryCondition, @PageableDefault(size = 10,page=1,sort = {"username","age"},direction = Sort.Direction.DESC) Pageable pageable){
System.out.println(userQueryCondition);
System.out.print(pageable.getPageSize());
System.out.println(pageable.getSort());
System.out.println(pageable.getOffset());
List<User> users = new ArrayList<>();
users.add(new User());
users.add(new User());
users.add(new User());
return users;
}
/**
* 在url中使用正則表達(dá)式
* @param id
* @return
*/
@GetMapping("/user/{id:\\d+}")
@JsonView(User.UserDetailView.class)
public User get(@PathVariable String id){
System.out.println(id);
User user = new User();
user.setUsername("tom");
return user;
}
}
- 完成步驟3赫悄,在不同Controller的方法上使用視圖
2.2.3 測(cè)試
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserControllerTest {
@Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mockMvc;
@Before
public void setup(){
//根據(jù)webApplicationContext構(gòu)建mockMvc
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@Test
public void whenQuerySuccess() throws Exception {
String result = mockMvc.perform(MockMvcRequestBuilders.get("/user")
.param("username","tom")
.param("age","11")
.param("ageTo","30")
.param("page","20")
.param("pageSize","100")
.param("sort","age,desc")
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.length()").value(3))
.andReturn().getResponse().getContentAsString();
System.out.println(result);
}
/**
* 請(qǐng)求成功邏輯測(cè)試
* @throws Exception
*/
@Test
public void wherGetSuccess() throws Exception {
String result = mockMvc.perform(MockMvcRequestBuilders.get("/user/1")
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.username").value("tom"))
.andReturn().getResponse().getContentAsString();
System.out.println(result);
}
/**
* 路徑正則表達(dá)式的匹配規(guī)則測(cè)試
* @throws Exception
*/
@Test
public void whenGetFail() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/user/a")
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(MockMvcResultMatchers.status().is4xxClientError());
}
}
- 測(cè)試結(jié)果
- 查詢(xún)?nèi)康姆祷亟Y(jié)果沒(méi)有
password
字段
[{"username":null,"age":null},{"username":null,"age":null},{"username":null,"age":null}]
- 查詢(xún)?cè)斍榈姆祷亟Y(jié)果有
password
字段
{"username":"tom","password":null,"age":null}