轉載@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的兩個視圖接口UserSimpleView
和UserDetailView
,UserDetailView
繼承UserSimpleView
,UserDetailView
擁有視圖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的方法上使用不同視圖
測試