@JsonView的使用

2023-11-18

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

注意是: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视图的会把密码给打印出来

 

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

@JsonView的使用 的相关文章

随机推荐

  • Seata: 运行nacos-config.sh报Please check the cluster status的总结

    一 看所在的机器是否安装了curl并正常工作 二 检查nacos是否能正常访问 三 看如下命令结果是否异常 根据实际情况调整nacos地址 curl X POST http 127 0 0 1 8848 nacos v1 cs config
  • 27 openEuler管理网络-通过ifcfg文件配置网络

    文章目录 27 openEuler管理网络 通过ifcfg文件配置网络 27 1 配置静态网络 27 2 配置动态网络 27 3 配置默认网关 27 openEuler管理网络 通过ifcfg文件配置网络 说明 通过ifcfg文件配置的网络
  • MySQL-mysql 8.0.11安装教程

    转载 https www cnblogs com laumians notes p 9069498 html 另外在奉上我自己搜索到的两个mysql安装网站 1 https dev mysql com doc refman 8 0 en d
  • G - Five-In-a-Row

    B Five In a Row time limit per test 1 second memory limit per test 256 megabytes input standard input output standard ou
  • 好长时间不看,php魔术变量又忘了,赶紧总结下

    看到了wordpress的这行代码想起来的 define WP USE THEMES true Loads the WordPress Environment and Template require dirname FILE wp blo
  • AsyncTask源码梳理及总结

    结合Android 7 0源码 全面解析AsyncTask的源码 梳理AsyncTask使用过程中的一些注意事项 分析源码之前 我们先来梳理一下使用 AsyncTask使用示例 public class MainActivity exten
  • VS Code-此时不应有 &

    描述 用vs code运行python代码时 报 此时不应有 解决方式 ctrl 调出终端 将默认终端设置成powershell 退出 重新加载代码
  • 《七天数据埋点之旅》第一天:初识埋点

    0x00 前言 本篇为 七天数据埋点之旅 的第一篇 通过阅读本篇 你将获得以下三方面的知识 什么是埋点 埋点的用途 埋点的分类 0x01 什么是埋点 数据埋点是数据采集的一种重要方式 主要用来记录和收集终端用户的操作行为 其基本原理是在Ap
  • 1.3端口扫描:利用Nmap工具进行端口扫描

    1 预备知识 Nmap介绍 nmap的功能 端口扫描 主机发现 服务 版本识别 操作系统识别 网络路由跟踪 Nmap脚本引擎 nmap的扫描方式 Half open scanning 默认扫描方式 TCP connect TCP ACK s
  • 正则匹配微信昵称

    x 4e00 x 9fa5 a zA Z0 9 2 32 u x 1F600 x 1F64F x 1F300 x 1F5FF x 1F680 x 1F6FF x 2600 x 26FF x 2700 x 27BF u
  • PHP使用PhpSpreadsheet库的操作Excel表格

    一 PhpSpreadsheet 介绍 PhpSpreadsheet是一个用纯PHP编写的库 提供了一组类 使您可以读取和写入不同的电子表格文件格式 PhpSpreadsheet提供了丰富的API接口 可以设置诸多单元格以及文档属性 包括样
  • 全国通用DNS服务器

    全国各地电信铁通DNS服务器地址 北京 202 96 199 133 202 96 0 133 202 106 0 20 202 106 148 1 202 97 16 195上海 202 96 199 132 202 96 199 133
  • JavaSE面试总结

    网络 反射 网络 OSI 的七层模型都有哪些 TCP与UDP区别 什么是三次握手四次挥手 socket编程 time wait状态如何产生 tcp为什么要三次握手 TCP如何保证可靠传输 什么是 TCP 粘包 它的产生原因以及解决方法 TC
  • 微信小程序 顶部自定义导航 “navigationStyle“: “custom“ 真机iPhone6/7/8不显示胶囊按钮

    微信小程序 顶部自定义导航 navigationStyle custom 要实现这种效果图 1 在哪个页面上实现自定义导航栏就在哪个页面的 json 文件中写上 navigationStyle custom 如果在app json写那就是所
  • 30多岁挨踢人要转行的焦虑,是真的吗

    30多岁挨踢人要转行的焦虑 是真的吗 从菜鸟到高级都在焦虑的一个问题 到了30多岁还没有做出点成就的话 就只能转行了 诸如做管理 创业开饭馆等等 我一直对此观点持保留态度 粗略看国内挨踢的发展历程 2000年出现第一次泡沫 往前推的话 有规
  • 2023,DaaS驶入“AI大航海时代”

    2023 制胜 已然成为所有行业 企业的共同命题 随着数字化行至中程 数据壁垒逐渐被打破 DaaS作为企业增长问题的解法 再次被看到 作者 斗斗 编辑 皮爷 出品 产业家 2002年 在竞争激烈的美国职业棒球联盟 奥克兰运动家队无论在人员和
  • 关于C的预编译 宏定义 的一些使用[不断积累中]

    头文件 防止重复包含 根据 define 和条件编译 ifdef ifndef else endif 最经常的使用是 头文件 防止重复包含 但是 使用 pragma once 更好 现在 gcc cl exe 都支持 它不但代码更少 而且不
  • 点云分割介绍

    PCL之点云的分割 参考博客 https www yuque com huangzhongqing pcl kg7wvi peMqz https blog csdn net lizhengze1117 article details 890
  • 股权投资模型-CAPM模型和PEG模型(内附示例数据)

    一 CAPM模型 1 数据来源 示例数据附在分享文件中 2 数据年份 2000 2019年 3 数据指标 资本资产定价模型 Capital Asset Pricing Model 简称CAPM 是由美国学者威廉 夏普 William Sha
  • @JsonView的使用

    看到一个新的注解以前没有用过 记录一下使用方法 注意是 com fasterxml jackson annotation JsonView JsonView可以过滤pojo的属性 使Controller在返回json时候 pojo某些属性不