@JsonView的使用


1.使用場景

在某一些請求返回的JSON中,我們並不希望返回某些字段。而在另一些請求中需要返回某些字段。
例如:

 

  • 查詢列表請求中,不返回password字段
  • 獲取用戶詳情中,返回password字段

用戶類

public class User
{
    private Integer id;
    private String username;
    private String password;
    private Date birthday;
}

2.實現

2.1 @JsonView的使用步驟

  • 1.使用接口來聲明多個視圖
  • 2.在值對象的get方法或屬性上指定視圖
  • 3.在Controller的方法上指定視圖


2.2 實現的具體代碼

(1)實體類 -- User

import com.fasterxml.jackson.annotation.JsonView; import lombok.Data; import org.hibernate.validator.constraints.NotBlank; import javax.validation.constraints.NotNull; import java.util.Date;  @Data public class User { public interface SimpleView{} public interface DetailView extends SimpleView{} @NotNull @JsonView(DetailView.class) private Integer id; @NotBlank(message = "參數username不能為空") @JsonView(SimpleView.class) private String username; @NotBlank(message = "參數password不能為空")  @JsonView(DetailView.class) private String password; @JsonView(DetailView.class) private Date birthday; }

上面定義了兩個視圖接口 UserSimpleView  和  UserDetailView, 其中UserDetailView繼承UserSimpleView,UserDetailView擁有視圖UserSimpleView的屬性;在相應的get方法或屬性上聲明JsonView;

(2)Controller的定義 -- UserController

@RestController @RequestMapping("/user") public class UserController { @GetMapping @JsonView(User.SimpleView.class) public List<User> queryList(User user, //給分頁對象設置默認值
                @PageableDefault(page = 2, size = 2, sort = "username,asc") Pageable pageable) { System.out.println(user); List<User> list = new ArrayList<>(); list.add(user); return list; } @GetMapping("/{id:\\d+}")  //正則表達式, 參數必須是全數字
    @JsonView(User.DetailView.class) public User getInfo(@PathVariable(name = "id") Integer userId){ User user = new User(); user.setId(userId); user.setUsername("Tom"); return user; } }

在controller的不同方法上使用不同的視圖;

(3)測試

@RunWith(SpringRunner.class) @SpringBootTest public class UserControllerTest { @Autowired private WebApplicationContext webApplicationContext; private MockMvc mockMvc;
@Before
public void setup(){ //根據webApplicationContext構建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); } /** * 請求成功邏輯測試 * @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); } /** * 路徑正則表達式的匹配規則測試 * @throws Exception */ @Test public void whenGetFail() throws Exception { mockMvc.perform(MockMvcRequestBuilders.get("/user/a") .contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(MockMvcResultMatchers.status().is4xxClientError()); } }

測試結果

(1)查詢全部的返回結果只有username字段;

(2)查詢詳情的返回結果所有字段都有;

 

 

 

 

  • 這里完成了步驟1和步驟2


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM