• @JsonView的使用


    @JsonView的使用

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

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.7.5</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.8</version>
    </dependency>

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.9.8</version>
    </dependency>

    1.使用场景

    在某一些请求返回的JSON中,我们并不希望返回pojo中的某些字段或全部字段。而在另一些请求中需要返回某些字段。

    2.实现

    2.1 @JsonView的使用步骤

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

    2.2 完整事例代码

    2.2.1User对象定义

    public class User{
    
        /**
         * 用户简单视图
         */
        public interface UserSimpleView{};
    
        /**
         * 用户详情视图
         */
        public interface UserDetailView extends UserSimpleView{};
    
        private String username;
    
        private String password;
    
        private String age;
    
        @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;
        }
    
        @JsonView(UserSimpleView.class)
        public String getAge() {
            return age;
        }
        
        public void setAge(String age) {
            this.age = age;
        }
    }
    • 这里完成了步骤1和步骤2
    • 定义了步骤1的两个视图接口UserSimpleViewUserDetailView,UserDetailView继承UserSimpleViewUserDetailView拥有视图UserSimpleView的属性
    • 完成了步骤2的在相应的get方法上声明JsonView

    2.2.2 定义UserController

    @RestController
    public class UserController {
    
        @GetMapping("/user")
        @JsonView({User.UserSimpleView.class})
        public List<User> query(UserQueryCondition userQueryCondition, @PageableDefault(size = 10,page=1,sort = {"username","age"},direction = Sort.Direction.DESC) Pageable pageable){
            System.out.println(userQueryCondition);
            System.out.print(pageable.getPageSize());
            System.out.println(pageable.getSort());
            System.out.println(pageable.getOffset());
            List<User> users = new ArrayList<>();
            users.add(new User());
            users.add(new User());
            users.add(new User());
            return users;
        }
    
        /**
         * 在url中使用正则表达式
         * @param id
         * @return
         */
        @GetMapping("/user/{id:\d+}")
        @JsonView(User.UserDetailView.class)
        public User get(@PathVariable String id){
            System.out.println(id);
            User user = new User();
            user.setUsername("tom");
            return user;
        }
    }
    • 完成步骤3,在不同Controller的方法上使用视图

    2.2.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());
        }
    
    
    }
    • 测试结果
    • 查询全部的返回结果没有password字段
    [{"username":null,"age":null},{"username":null,"age":null},{"username":null,"age":null}]
    • 查询详情的返回结果有password字段
    {"username":"tom","password":null,"age":null}
  • 相关阅读:
    纯CSS实现小三角提示信息
    PostGIS+QGIS+GeoServer+OpenLayers实现数据的存储、服务的发布以及地图的显示
    Arcgis for Js之Graphiclayer扩展详解
    Arcgis for JS扩展GraphicLayer实现区域对象的聚类统计与展示
    Arcgis for JS之Cluster聚类分析的实现(基于区域范围的)
    Arcgis for JS之Cluster聚类分析的实现
    Arcgis for Js之featurelayer实现空间查询和属性查询
    RESTful WebService入门
    使用 Spring 3 来创建 RESTful Web Services(转)
    基于Spring设计并实现RESTful Web Services(转)
  • 原文地址:https://www.cnblogs.com/dw3306/p/10925431.html
Copyright © 2020-2023  润新知