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

@JsonView的使用的更多相关文章

  1. 推荐两个谷歌的json-view插件(附带下载分享地址)

    1.JSONView 网盘下载地址:http://pan.baidu.com/s/1hrGlaVa 效果图: 2.JSON-handle 网盘下载地址:http://pan.baidu.com/s/1 ...

  2. Safari里使用JsonView

    这是第三方开发的一个Safari的jsonView,和chrome以及FF功能类似,现在已经更新到1.1版了. 传送门:https://github.com/rfletcher/safari-json ...

  3. chrome jsonView插件安装

    chrome 应用商店打不开,想装插件愁死人了. 今天想到一个好方法,以 jsonView插件为例分享一下. 1.打开 https://github.com : 2.搜索 jsonView 链接:ht ...

  4. 谷歌浏览器插件-jsonView插件安装与使用

    本文转载:http://www.bubuko.com/infodetail-700647.html 1 安装 1.打开 https://github.com : 2.搜索 jsonView 链接:ht ...

  5. 【Chrome插件】去掉因使用jsonView插件的弹出窗口"请停用以开发者模式运行的扩展程序"

    前言 小编最近使用jsonView插件时,每次打开谷歌浏览器都会弹出下面的窗口,上网搜索,找到一个非常有效的方法. 解决方法 一.新建一个文本文档 二.复制代码 <# : @echo off c ...

  6. 【JsonView工具】谷歌浏览器中安装JsonView扩展程序

    接口测试过程中,有时候要查看接口返回的数据(比如Get接口),为了更方便的查看,发现这个插件挺好用的. 实际开发工作中经常用到json数据,那么就会有这样一个需求:在谷歌浏览器中访问URL地址返回的j ...

  7. 谷歌浏览器中安装JsonView扩展程序

    实际开发工作中经常用到json数据,那么就会有这样一个需求:在谷歌浏览器中访问URL地址返回的json数据能否按照json格式展现出来. 比如,在谷歌浏览器中访问:http://jsonview.co ...

  8. 【转】让浏览器格式化显示JSON数据之chrome jsonView插件安装

    jsonView 用来让Chrome浏览器能格式化的显示JSON数据. 以上是网上找的方式,且试验成功! 步骤: 1.打开 https://github.com : 2.搜索 jsonView 链接: ...

  9. 使用@JsonView注解控制返回的Json属性

    我也是刚看到原来还可以这么玩,但是我还是习惯使用Dto,我总感觉这样做的话实体类耦合程度有点高.还是记录以下,万一今后用到了呢 ⒈在实体类中使用接口来声明该实体类的多个视图. ⒉在实体类的属性get方 ...

  10. Spring MVC中@JsonView的使用

    一.@JsonView注解的简介 @JsonView是jackson json中的一个注解,Spring webmvc也支持这个注解,它的作用就是控制输入输出后的json 二.@JsonView注解的 ...

随机推荐

  1. Java 函数式编程—@FunctionalInterface----functional interface

    单一函数接口,可以使用拉姆达表达式的形式具体化和实例化. 本质是将接口函数签名化. 如定义了一个函数式接口如下: @FunctionalInterface interface GreetingServ ...

  2. linq 获取不重复数据,重复数据 var unique = arr.GroupBy(o => o).Where(g => g.Count() == 1) .Select(g => g.ElementAt(0));

    static void Main(string[] args) { int[] arr = { 1, 3, 3, 3, 3, 4, 5, 4, 5, 8, 9, 3 }; //不重复 var uniq ...

  3. DLT645 1997 协议解析

    源码下载  -> 提取码 QQ:505645074 DLT645.zip 工具 源码 规约解析 DL/T645-07: 数据帧格式: 注意事项: (1)前导字节-一般在传输帧信息前,都要有0~4 ...

  4. 【IPHONE开发-OBJECTC入门学习】对象的归档和解归档

    转自:http://blog.csdn.net/java886o/article/details/9046967 #import <Foundation/Foundation.h> #im ...

  5. rt-thread can

    rt-thread stm32f10x-HAL can的驱动和应用.源码暂时还不支持,自己通过F4修改了一版 源码地址:https://gitee.com/gitee.thomas/rt_can rt ...

  6. 转cocopods的使用

    一.概要 iOS开发时,项目中会引用许多第三方库,CocoaPods(https://github.com/CocoaPods/CocoaPods)可以用来方便的统一管理这些第三方库. 二.安装 由于 ...

  7. [b0018] python 归纳 (四)_运算符重载

    # -*- coding: UTF-8 -*- """ 测试运算符重载 加法 总结: python 运算符表达式其实都是调用 类中方法 __xxx__ + <--- ...

  8. 转:Oracle的列转行函数:LISTAGG()

    先看示例代码: with temp as( select 'China' nation ,'Guangzhou' city from dual union all select 'China' nat ...

  9. linux 互斥锁和条件变量

    为什么有条件变量? 请参看一个线程等待某种事件发生 注意:本文是linux c版本的条件变量和互斥锁(mutex),不是C++的. mutex : mutual exclusion(相互排斥) 1,互 ...

  10. Pyqt5开发一款小工具(翻译小助手)

    翻译小助手 开发需求 首先五月份的时候,正在学习爬虫的中级阶段,这时候肯定要接触到js逆向工程,于是上网找了一个项目来练练手,这时碰巧有如何进行对百度翻译的API破解思路,仿造网上的思路,我摸索着完成 ...