注解@JsonView的使用

时间:2020-04-08
本文章向大家介绍注解@JsonView的使用,主要包括注解@JsonView的使用使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

转载@JsonView的使用 略有修改

1.使用场景

在某一些请求返回的JSON中,我们并不希望返回某些字段。而在另一些请求中需要返回某些字段。
例:获取用户信息

  • 查询列表请求中,不返回password字段
  • 获取用户详情中,返回password字段

2. 实践

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

新建springboot项目,引入web

定义返回数据对象

import com.fasterxml.jackson.annotation.JsonView;

/**
 * @author john
 * @date 2020/4/8 - 19:51
 */
public class User {

    /**
     * 用户简单视图
     */
    public interface UserSimpleView{};

    /**
     * 用户详情视图
     */
    public interface UserDetailView extends UserSimpleView{};

    private int id;
    private String username;
    private String password;

    @JsonView(UserSimpleView.class)
    public int getId() {
        return id;
    }

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

    @JsonView(UserSimpleView.class)
    public String getUsername() {
        return username;
    }

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

    public String getPassword() {
        return password;
    }

    @JsonView(UserDetailView.class)
    public void setPassword(String password) {
        this.password = password;
    }

    public User(int id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    }

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

这里完成了步骤1和步骤2

定义了步骤1的两个视图接口UserSimpleViewUserDetailView,UserDetailView继承UserSimpleViewUserDetailView拥有视图UserSimpleView的属性

完成了步骤2的在相应的get方法上声明JsonView

定义访问控制器

import com.example.demo.bean.User;
import com.fasterxml.jackson.annotation.JsonView;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

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

/**
 * @author john
 * @date 2020/4/8 - 19:55
 */
@RestController
public class UserController {

    @GetMapping("/user")
    @JsonView({User.UserSimpleView.class})
    public List<User> query() {
        List<User> users = new ArrayList<>();
        users.add(new User(1, "john", "123456"));
        users.add(new User(2, "tom", "123456"));
        users.add(new User(3, "jim", "123456"));
        return users;
    }

    /**
     * 在url中使用正则表达式
     *
     * @param id
     * @return
     */
    @GetMapping("/user/{id:\\d+}")
    @JsonView(User.UserDetailView.class)
    public User get(@PathVariable String id) {
        User user = new User(1, "john", "123456");
        user.setUsername("tom");
        return user;
    }
}

完成步骤3,在不同Controller的方法上使用不同视图

测试

原文地址:https://www.cnblogs.com/ifme/p/12662406.html