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

最新文章

  1. 替换CENTOS自带的yum源为网易163镜像源
  2. 美妙的 CSS3 动画!一组梦幻般的按钮效果
  3. jquery学习笔记---Dom操作
  4. 指定winfrom程序配置文件
  5. Can&#39;t find keyplane that supports type 4 for keyboard iPhone-Portrait-NumberPad; using 3876877096_Portrait_iPhone-Simple-Pad_Default
  6. 文本编辑器vim
  7. 【转载】写runat=&quot;server&quot;有什么用
  8. Makefile 快速入门
  9. 如何在PSD中准确切出图片
  10. Git中从远程的分支获取最新的版本到本地
  11. kafka学习(四)-Topic &amp; Partition
  12. 从数据库读取二进制图片,img标签显示图片
  13. 【Hexo】Hexo+Github构建个人博客 (五):错误集
  14. MongoDB 搭建可复制群集
  15. navigator的一些冷知识
  16. 编写高性能.NET程序-《Concurrency in .NET》(1)- 为什么要读这本书?
  17. Python基础:十、用户交互
  18. Django 中的Form、ModelForm
  19. C#语言不常用语法笔记
  20. Linux之svn数据备份、还原及迁移

热门文章

  1. java架构之路(mysql底层原理)Mysql之Explain使用详解
  2. C# based on PdfSharp to split pdf files and get MemoryStream C#基于PdfSharp拆分pdf,并生成MemoryStream
  3. WPF toolkit AutoCompleteBox
  4. Java开发在线考试系统 使用ssh框架编写源码
  5. PHP-FPM Fastcgi 未授权访问漏洞
  6. maven 学习---Maven快照
  7. Git内部原理浅析
  8. Android View篇之自定义验证码输入框
  9. selenium和AutoIt工具辅助下载和上传
  10. Bootstrap Table列宽拖动的方法