注解@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的方法上使用不同視圖

測試


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM