@JsonView的使用

@JsonView的使用

注意是:com.fasterxml.jackson.annotation.JsonView

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.7.5</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.8</version>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.9.8</version>
</dependency>web

 

1.使用場景

在某一些請求返回的JSON中,咱們並不但願返回pojo中的某些字段或所有字段。而在另外一些請求中須要返回某些字段。正則表達式

2.實現

2.1 @JsonView的使用步驟

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

 

2.2 完整事例代碼

2.2.1User對象定義json

 

public class User{

    /**
     * 用戶簡單視圖
     */
    public interface UserSimpleView{};

    /**
     * 用戶詳情視圖
     */
    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的兩個視圖接口UserSimpleViewUserDetailView,UserDetailView繼承UserSimpleViewUserDetailView擁有視圖UserSimpleView的屬性
  • 完成了步驟2的在相應的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中使用正則表達式
     * @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 測試

@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());
    }


}

 

  • 測試結果
  • 查詢所有的返回結果沒有password字段
[{"username":null,"age":null},{"username":null,"age":null},{"username":null,"age":null}]

 

  • 查詢詳情的返回結果有password字段
{"username":"tom","password":null,"age":null}
相關文章
相關標籤/搜索