JsonView use and JsonIgnore

 Description: In a multi-use item that longitudinal front and rear ends of the separation method of data transmission is used in almost all forms of json

          So we return in the form of time specifically for json sometimes you need to ignore certain fields in the query data, how do we do that? ? ? ? ?

          Json conversion method generally used in two and is fastjson two separate jackjson

1, directly into json time never need to convert the current field as the json

    I used here @JsonIgnore jackjson

    Use

Controller

Output:

 

 

 

 The results can be seen when the door I add @JsonIgnore notes in a certain time we will find a property designed for json result set object which does not include our attribute add annotations

 

2, when we returned in the result set to be ignored to a certain attribute and ignore the return of property details information we can use @JsonView property

     @JsonView property usage rules

      1) You must use the interface to declare multiple views

     2) get method specified view on the value of the object

     3) Specify view on the designated controller

     Specific case are as follows:

entity:  

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的数据只是添加了当前注解的属性字段  没有添加的不会展示出来

 

 

 

    

  

Guess you like

Origin www.cnblogs.com/lwdmaib/p/12241535.html
use
use