@JsonView的使用
阅读原文时间:2023年07月10日阅读:1

1.使用场景

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

  • 查询列表请求中,不返回password字段
  • 获取用户详情中,返回password字段

用户类

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

2.实现

  • 1.使用接口来声明多个视图
  • 2.在值对象的get方法或属性上指定视图
  • 3.在Controller的方法上指定视图

(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 queryList(User user,
//给分页对象设置默认值
@PageableDefault(page = 2, size = 2, sort = "username,asc") Pageable pageable)
{
System.out.println(user);
List 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

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章