• @JsonView的使用


    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
  • 相关阅读:
    SpringBoot项目中遇到的BUG
    关于Unsupported major.minor version 52.0报错问题解决方案
    spring官网上下载历史版本的spring插件,springsource-tool-suite
    构建微服务:Spring boot 入门篇
    Spring Cloud 入门教程(一): 服务注册
    SpringCloud是什么?
    ubuntu下查看windows的 txt 文件乱码
    Ubuntu 14.04 LTS中怎样安装fcitx中文输入法
    eclipse调用jni
    Ubuntu 12.04 分区方案(仅供参考)
  • 原文地址:https://www.cnblogs.com/yufeng218/p/11795652.html
Copyright © 2020-2023  润新知