看到一个新的注解以前没有用过,记录一下使用方法。

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

@JsonView可以过滤pojo的属性,使Controller在返回json时候,pojo某些属性不返回,比如User的密码,一般是不返回的,就可以使用这个注解。

@JsonView使用方法:

  1,使用接口来声明多个视图

  2,在pojo的get方法上指定视图

  3,在Controller方法上指定视图

例子:条件查询时候不返回用户的密码,查看详情时候返回用户的密码

User:

package com.imooc.dto;

import com.fasterxml.jackson.annotation.JsonView;

public class User {

    public interface UserSimpleView {};
public interface UserDetailView extends UserSimpleView{}; //继承 private String username; private String password; //UserSimpleView视图有
@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;
} @Override
public String toString() {
return "User [username=" + username + ", password=" + password + "]";
} }

Controller:

package com.imooc.web.controller;

import java.util.ArrayList;
import java.util.List; import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import com.fasterxml.jackson.annotation.JsonView;
import com.imooc.dto.User;
import com.imooc.dto.UserQueryCondition; @RestController
@RequestMapping("/user")
public class UserController { /**
* @Description: 条件查询
* @param @param condition
* @param @param pageable
* @param @return
* @return List<User>
* @throws
* @author lihaoyang
* @date 2018年2月24日
*/
@GetMapping("query")
@JsonView(User.UserSimpleView.class)
public List<User> query(
//@RequestParam(value="username",required=false,defaultValue="lhy") String username
UserQueryCondition condition , Pageable pageable){
// System.err.println(username);
System.err.println(condition.toString());
System.err.println(pageable.toString()); List<User> users = new ArrayList<User>();
users.add(new User());
users.add(new User());
users.add(new User());
return users;
} /**
* 详情
* @Description: TODO
* @param @param id
* @param @return
* @return User
* @throws
* @author lihaoyang
* @date 2018年2月24日
*/
@GetMapping("detail/{id:\\d+}") //{}里可以是正则,匹配数字
// @GetMapping("detail/{id}")
@JsonView(User.UserDetailView.class)
public User getInfo(@PathVariable(value="id",required=true) String id){
System.err.println(id);
User user = new User();
user.setUsername("tom");
return user;
} }

测试用例:

package com.imooc.web.controller;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext; @RunWith(SpringRunner.class)
@SpringBootTest
public class UserControllerTest { @Autowired
private WebApplicationContext webCtx; //伪造mvc
private MockMvc mockMvc; @Before
public void setup(){
mockMvc = MockMvcBuilders.webAppContextSetup(webCtx).build();
} /**
* 查询
*/
@Test
public void whenQuerySuccess() throws Exception{
String result = mockMvc.perform(MockMvcRequestBuilders.get("/user/query") //路径
.param("page", "10") //参数
.param("size", "12")
.param("sort", "age,desc")
.param("username", "xiaoming")
.param("age", "18")
.param("ageTo", "40")
.param("other", "otherProperty")
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(MockMvcResultMatchers.status().isOk()) //状态码200
.andExpect(MockMvcResultMatchers.jsonPath("$.length()").value(3))//长度为3,具体查看github的jsonPath项目
.andReturn().getResponse().getContentAsString();
System.err.println(result);
} /**
* 详情
*/
@Test
public void whenGetInfoSuccess() throws Exception{
String result = mockMvc.perform(MockMvcRequestBuilders.get("/user/detail/1")
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.username").value("tom"))
.andReturn().getResponse().getContentAsString();
System.err.println(result);
} /**
* 详情失败
*/
@Test
public void whenGetInfoFail() throws Exception{
mockMvc.perform(MockMvcRequestBuilders.get("/user/detail/a") //匹配正则
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(MockMvcResultMatchers.status().is4xxClientError()); } }

打印结果:使用UserDetailView视图的会把密码给打印出来

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

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

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

  2. 利用@jsonView注解来实现自定义返回字段

    业务场景:比如说一个User对象,有两个字段,一个username,一个password,有一个获取用户信息的接口要返回这个User列表,但是不想要这个User列表的password字段. 还有一个接 ...

  3. @JsonView注解指定返回的model类中显示的字段

    1.User类 package com.imooc.model; import com.fasterxml.jackson.annotation.JsonView; /** * @author oy ...

  4. jackson annotations注解详解 (zhuan)

    http://blog.csdn.net/sdyy321/article/details/40298081 ************************************** 官方WIKI: ...

  5. Spring MVC中@JsonView的使用

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

  6. SpringMvc @JsonView 使用方式

    准确来说,@JsonView注解不是Spring的,它位于jackson-annotation包中: 作用:SpringMvc使用@ResponseBody将结果以json返回客户端,  有些实体类的 ...

  7. Spring 4 官方文档学习 Web MVC 框架

    1.介绍Spring Web MVC 框架 Spring Web MVC 框架是围绕DispatcherServlet设计的,所谓DispatcherServlet就是将请求分发到handler,需要 ...

  8. SpringMvc @ResponseBody

    一.@Response使用条件 二. @Response在最小配置.jackson的jar包情况下,json中包含的日期类型字段都是以时间戳long类型返回 三. Jack序列化对象转为JSON的限制 ...

  9. Spring 4 官方文档学习(十一)Web MVC 框架

    介绍Spring Web MVC 框架 Spring Web MVC的特性 其他MVC实现的可插拔性 DispatcherServlet 在WebApplicationContext中的特殊的bean ...

随机推荐

  1. HQL进阶

    1.HQL查询性能优化 1.1.避免or操作 1.1.1.where子句包含or操作,执行时不使用索引 from Hose where street_id='1000' or street_id='1 ...

  2. 解决Web Uploader上传文件和图片 延迟和not defined

    1.出现list not define时,var $list = $("#fileList"); 2.选择文件框有延迟,可能是因为选择文件类型过多 mimeTypes: 'imag ...

  3. day03(接口,多态)

    接口:            概念:是功能的集合,可以当做引用数据类型的一种.比抽象类更加抽象. 接口的成员:               成员变量:必须使用final修饰 默认被 public &a ...

  4. Codeforces801A Vicious Keyboard 2017-04-19 00:16 241人阅读 评论(0) 收藏

    A. Vicious Keyboard time limit per test 2 seconds memory limit per test 256 megabytes input standard ...

  5. hdu 5062 单峰数(12321)的个数

    http://acm.hdu.edu.cn/showproblem.php?pid=5062 模拟筛出对称单峰数(12321)的个数,水题 #include <cstdio> #inclu ...

  6. 分离 桂林电子科技大学第三届ACM程序设计竞赛

    链接:https://ac.nowcoder.com/acm/contest/558/H 来源:牛客网 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 262144K,其他语言5242 ...

  7. matlab中使用正弦波合成方波(带动画)

    x=:*pi; :: s=; ::step s = s+/i*sin(i*x); end plot(s);set(figure(),'visible','off'); filename=[num2st ...

  8. sklearn使用小记GridSearchCV

    def test_grid_search(): from sklearn import datasets,svm iris = datasets.load_iris() parameters = {' ...

  9. C#使用cplex求解简单线性规划问题(Cplex系列-教程二)

    若还未在项目中添加cplex的引用,可以参阅上一篇文章.本文主要介绍利用C#求解线性规划的步骤,对线性规划模型进行数据填充的两种方法,以及一些cplex函数的功能和用法.包括以下几个步骤: 描述 先花 ...

  10. 使用docker来部署asp.net core的程序

    使用docker来部署asp.net core程序 暂不介绍docker是个什么东西?不知道的自己百度. 第一步安装docker: 我的docker是装在centos7系统上,windows上我的也用 ...