咱們來描述一個這樣的業務需求,首先有兩個URL,/A:爲獲取用戶詳情信息包含用戶的全部字段(用戶名,密碼),/B:爲獲取用戶信息字段(只要用戶名),怎麼處理呢?可能會想到建一個USER類而後返回不一樣的屬性。可是這樣寫法確實Low的一逼。@JsonView能夠十分方便的解決以上問題。下面我來介紹一下@JsonView。java
@JsonView是jackson json中的一個註解,Spring mvc一樣支持這個註解,它的做用就是控制輸入輸出後的json。json
import org.hibernate.validator.constraints.NotBlank; import com.fasterxml.jackson.annotation.JsonView; public class User { //聲明通常視圖接口 只容許這個視圖返回用戶名屬性 public interface UserSimpView{}; //聲明完整視圖接口 容許返回用戶名密碼屬性 因爲集成了通常視圖接口 含義是擁有了通常視圖所具備的返回屬性 public interface UserDetailView extends UserSimpView{}; private Integer Id; private String userName; private String passWord; public User() { } public User(Integer Id, String userName, String passWord) { this.Id = Id; this.userName = userName; this.passWord = passWord; } @JsonView(UserSimpView.class) public Integer getId() { return Id; } public void setId(Integer id) { Id = id; } @JsonView(UserSimpView.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 [Id=" + Id + ", userName=" + userName + ", passWord=" + passWord + "]"; } }
@RestController @RequestMapping("/user") public class UserController { @GetMapping(produces="application/json;charset=UTF-8") @JsonView(UserDetailView.class) public List getUserAll(@RequestParam("token") String token){ List<User> userList = new ArrayList<>(); userList.add(new User(1,"二十歲之後特殊視圖0","123456特殊視圖")); userList.add(new User(2,"二十歲之後特殊視圖1","qweqwe特殊視圖")); userList.add(new User(3,"二十歲之後特殊視圖2","asdgdd特殊視圖")); return userList; }
當我使用完整視圖的狀況下mvc
@RestController @RequestMapping("/user") public class UserController { @GetMapping(produces="application/json;charset=UTF-8") @JsonView(UserDetailView.class) public List getUserAll(@RequestParam("token") String token){ List<User> userList = new ArrayList<>(); userList.add(new User(1,"二十歲之後特殊視圖0","123456完整視圖")); userList.add(new User(2,"二十歲之後特殊視圖1","qweqwe完整視圖")); userList.add(new User(3,"二十歲之後特殊視圖2","asdgdd完整視圖")); return userList; }
返回結果爲:app
當我使用特殊視圖的狀況下ide
@RestController @RequestMapping("/user") public class UserController { @GetMapping(produces="application/json;charset=UTF-8") @JsonView(UserSimpView.class) public List getUserAll(@RequestParam("token") String token){ List<User> userList = new ArrayList<>(); userList.add(new User(1,"二十歲之後特殊視圖0","123456完整視圖")); userList.add(new User(2,"二十歲之後特殊視圖1","qweqwe完整視圖")); userList.add(new User(3,"二十歲之後特殊視圖2","asdgdd完整視圖")); return userList; }
返回結果爲:測試