同一个对象,在不同的场景,返回不同的属性,如getUserById返回User对象包含password值,而getAllUsers返回User集合,不包含password值(通过接口查看显示,序列化的时候直接忽略该属性,而非返回null),这些场景称为视图,使用JsonView:
三个步骤:
1.通过在对象中定义多个接口来定义多个视图(场景),注:子接口会把继承的父接口展示的属性也展示
3.在controller方法上指定视图(场景)
package
com.example.security.entity
;
import
com.fasterxml.jackson.annotation.
JsonView
;
public class
User {
/**
* 步骤1
*/
public interface
UsernameView {}
public interface
UsernamePasswordView
extends
UsernameView {}
private
String
username
;
private
String
password
;
/**
* 步骤2
*
@return
*/
@JsonView
(UsernameView.
class
)
public
String
getUsername
() {
return
username
;
}
public void
setUsername
(String username) {
this
.
username
= username
;
}
/**
* 步骤2
*
@return
*/
public
String
getPassword
() {
return
password
;
}
public void
setPassword
(String password) {
this
.
password
= password
;
}
}
/**
* 步骤3
*
@return
*/
@RequestMapping
(
"/users"
)
@JsonView
(User.UsernameView.
class
)
public
List<User>
users
() {
return
Arrays.
asList
(
new
User(
"wzs"
,
"923286"
)
,
new
User(
"wmm"
,
"mm615678"
)
,
new
User(
"root"
,
"iMC123"
))
;
}
@GetMapping
(
"/user"
)
@JsonView
(User.UsernamePasswordView.
class
)
public
User
user
(User user) {
return
user
;
}