JsonView 与JsonIgnore 使用

 简述:现在项目多采用前后分离方式  那么前后端的数据传输几乎都采用的是json形式的

          那么我们在查询数据返回专为json的形式时候有时候需要忽略某些字段,我们如何来做那?????

          通常采用的json 转换方式有两种分别是fastjson  和jackjson两种

1、直接转为json时候任何时候都不需要当前字段做为json转换

    @JsonIgnore   我这里采用的jackjson

    使用方式

控制器

输出结果:

 

 

 

 分析结果可知  当我门在某一个属性添加@JsonIgnore注解的时候  我们会发现专为json的结果集对象里面不包含我们添加了注解的属性

 

2、当我们返回结果集中要忽略到某一属性  在返回的详情信息中又包含忽略的属性  我们可以采用@JsonView属性

     @JsonView属性使用规则

      1)必须使用接口声明多个视图

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

     3)在指定的控制器上指定视图

     具体案例如下:

实体:  

package lwd.security.dto;


import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonView;
import jdk.nashorn.internal.ir.annotations.Ignore;

public class User {

    /**
     * 定义一个简单视图
     */
    public interface UserSimpleView{};

    /**
     *  定义一个详细视图  继承简单视图
     */
    public interface UserDetailView extends UserSimpleView{};

    private String username;

    private String password;

    private Integer age;
    @JsonIgnore
    private String email;

    /**
     *  指定视图
     * @return
     */
    @JsonView(UserSimpleView.class)
    public String getUsername() {
        return username;
    }

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

    /**
     * 指定视图
     * @return
     */
    @JsonView(UserDetailView.class)
    public String getPassword() {
        return password;
    }

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

控制器定义:

package lwd.security.user.controller;

import com.fasterxml.jackson.annotation.JsonView;
import lwd.security.dto.User;
import lwd.security.dto.UserQueryCondition;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;

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.RequestMethod;

import org.springframework.web.bind.annotation.RestController;


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

@RestController
public class UserController {


    /**
     *  当前控制器中采用了简单视图
     * @param condition
     * @return
     */
    @RequestMapping(value = "/user",method = RequestMethod.GET)
    @JsonView(User.UserSimpleView.class)
    public List<User> query(UserQueryCondition condition){

        System.out.println(ReflectionToStringBuilder.toString(condition, ToStringStyle.MULTI_LINE_STYLE));

        List<User> users = new ArrayList<>();
        users.add(new User());
        users.add(new User());
        users.add(new User());
        return users;
    }

    /**
     *  url采用正则表达式形式  以及jsonview使用  指定了详情视图
     * @param id
     * @return
     */
    @GetMapping("/user/{id:\\d+}")
    @JsonView(User.UserDetailView.class)
    public User getInfo(@PathVariable(value = "id")Integer id){
        return new User();
    }

    /**
     * 实体忽略属性 jsonIgnore 形式
     * @param id
     * @return
     */
    @GetMapping(value = "/user/get/{id}")
    public User getDetail(@PathVariable(value = "id")String id){
        return new User();
    }



}

单元测试:

package lwd.security.controller;

import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.results.ResultMatchers;
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.MockMvcBuilder;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.ResultActions;
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;

import java.awt.*;

@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 {

        mockMvc.perform(MockMvcRequestBuilders.get("/user")
                .param("username","1111")
                .contentType(MediaType.APPLICATION_JSON))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.jsonPath("$.length()").value(3));

    }

    /**
     * 正则匹配信息
     * @throws Exception
     */
    @Test
    public void whenQuery4XXError() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.get("/user/1")
                .contentType(MediaType.APPLICATION_JSON_UTF8))
                .andExpect(MockMvcResultMatchers.status().isOk());

    }

    /**
     * 采用简单视图方式
     * @throws Exception
     */
    @Test
    public void whenQueryJsonViewInfo() throws Exception {
        String result = mockMvc.perform(MockMvcRequestBuilders.get("/user/1")
                .contentType(MediaType.APPLICATION_JSON_UTF8))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andReturn().getResponse().getContentAsString();
        System.out.println(result);
    }

    /**
     * 采用详细视图方式
     * @throws Exception
     */
    @Test
    public void whenQueryJsonViewDetailInfo() throws Exception {
        String result = mockMvc.perform(MockMvcRequestBuilders.get("/user")
                .contentType(MediaType.APPLICATION_JSON_UTF8))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andReturn().getResponse().getContentAsString();
        System.out.println(result);
    }

    /**
     * 采用属性忽略方式
     * @throws Exception
     */
    @Test
    public void whenQueryIgnore() throws Exception {
        String result = mockMvc.perform(MockMvcRequestBuilders.get("/user/get/1")
                .contentType(MediaType.APPLICATION_JSON_UTF8))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andReturn().getResponse().getContentAsString();

        System.err.println(result);
    }
}

指定详细视图方式结果集:

 

指定简单视图方式结果集:

 

@JsonView注解  最终专为json的数据只是添加了当前注解的属性字段  没有添加的不会展示出来

 

 

 

    

  

posted @ 2020-01-29 21:32  liuwd  阅读(920)  评论(0编辑  收藏  举报