Spring MVC中@JsonView的使用

一、@JsonView注解的简介

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

二、@JsonView注解的使用步骤

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

package com.knyel.dto;

public class User {

    public interface UserSimpleView {};
    public interface UserDetailView extends UserSimpleView {};

    private String username;
    private  String password;

    public String getUsername (){
        return username;
    }

    public void setUsername (String username){
        this.username = username;
    }

    public String getPassword (){
        return password;
    }

    public void setPassword (String password){
        this.password = password;
    }

    @Override
    public String toString (){
        return "User{" + "username='" + username + '\'' + ", password='" + password + '\'' + '}';
    }
}

 

2.在值对象的get方法上指定视图


package com.knyel.dto;

import com.fasterxml.jackson.annotation.JsonView;

public class User {

    public interface UserSimpleView {};
    public interface UserDetailView extends UserSimpleView {};

    private String username;
    private  String password;
    @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 + '\'' + '}';
    }
}

 

3.在controller方法上指定视图


package com.knyel.wb.controller;

import com.fasterxml.jackson.annotation.JsonView;
import com.knyel.dto.User;
import com.knyel.dto.UserQueryCondition;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.data.domain.Pageable;

import java.util.ArrayList;
import java.util.List;

@RestController
public class UserController {
    @RequestMapping(value = "/user",method = RequestMethod.GET)
    @JsonView(User.UserSimpleView.class)
    public List<User> query(UserQueryCondition userQueryCondition, @PageableDefault(page=1,size=10,sort="username,asc") Pageable pageable){
        System.out.println(pageable.getPageNumber());
        System.out.println(pageable.getSort());
        System.out.println(pageable.getPageSize());
        System.out.println(userQueryCondition.toString());
        List<User> users=new ArrayList<>();
        users.add(new User());
        users.add(new User());
        users.add(new User());
        return  users;
    }
    @RequestMapping(value="/user/{id:\\d+}",method = RequestMethod.GET)
    @JsonView(User.UserDetailView.class)
    public User getInfo(@PathVariable String id){
        User user=new User();
        user.setUsername("knyel");
        System.out.println(user);
        return user;
    }
}

4.测试类


package com.knyel.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 wac;

    private MockMvc mockMvc;

    @Before
    public void setUp (){
        mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
    }

    @Test
    public void whenQuerySuccess () throws Exception{
        String result=mockMvc.perform(MockMvcRequestBuilders.get("/user")
                .param("username","knyel")
                .param("age","18")
                .param("ageTo","60")
                .param("phone","110")
                .param("size","15")
                .param("page","2")
                .param("sort","age,desc")
                .contentType(MediaType.APPLICATION_JSON_UTF8))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.jsonPath("$.length()").value("3"))//查询的根元素,例如$.length()代表整个传过来的json的文档
                .andReturn().getResponse().getContentAsString();
        System.out.println(result);
    }

    @Test
    public void whenGenInfoSuccess() throws Exception{
        String result=mockMvc.perform(MockMvcRequestBuilders.get("/user/1")
        .contentType(MediaType.APPLICATION_JSON_UTF8))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.jsonPath("$.username").value("knyel"))
                .andReturn().getResponse().getContentAsString();
        System.out.println(result);
    }

    @Test
    public void whenGetInfoFail() throws Exception{
        mockMvc.perform(MockMvcRequestBuilders.get("/user/a")
        .contentType(MediaType.APPLICATION_JSON_UTF8))
                .andExpect(MockMvcResultMatchers.status().is4xxClientError());
    }
}

whenQuerySuccess的返回值为:
[{"username":null},{"username":null},{"username":null}]
whenGetInfoSuccess的返回值为:
{"username":"knyel","password":null}

对于带有分页查询的例子

  @Test
    public void whenGetDwbzxxSuccess() throws Exception{
        
        String result=mockMvc.perform(MockMvcRequestBuilders.get("/dwbzxx/findDwbzxx")
                .param("limit", "10")
                .param("offset", "0")
                .param("dwdmYj", "1399")
                .param("dwdmEj", "28e516432383411b8fac66a2b8ff08bf")
                .contentType(MediaType.APPLICATION_JSON))
                .andReturn().getResponse().getContentAsString();
        
        System.out.println(result);
    }

介绍

@JsonView是Spring中的一个注解,用于在不同的请求中返回不同的视图。例如,在请求/users中会返回一个包含基本用户信息的List,此时不应该把所有的用户密码等详情返回出来。但是,当请求某一个用户的详情/user/{id:\\+d}时候,则需要返回该用户的所有信息。此时,可以通过JsonView注解来表明如何在不同的请求中返回什么样的视图。

JsonView使用步骤

S1:使用接口来声明多个视图
S2:在返回值对象的get方法上指定视图
S3:在Controller方法上指定视图

一个完整的实例

1. 返回值类:User类

public class User {

// 使用接口来声明多个视图 
    public interface UserSimpleView{};
    public interface UserDetailView extends UserSimpleView{};

    private Integer id;
    private int age;
    private String userName;
    private String password;

//在返回值对象的get方法上指定视图  
    @JsonView(UserSimpleView.class)
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    @JsonView(UserSimpleView.class)
    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = 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;
    }
}

2. Controller类

@RestController
@RequestMapping(value = "/rest")
public class DemoController {
//在Controller方法上指定视图
    @GetMapping("/user")
    @JsonView(User.UserSimpleView.class)
    public User getUser(){
        User user = new User();
        user.setId(1);
        user.setUserName("liyubo");
        user.setAge(25);
        user.setPassword("yyYYuswoYMOS==s");

        return user;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值