Jackson JSON
Spring支持Jackson JSON库。
JSON视图
Spring WebFlux 内置支持Jackson 的序列化视图,允许仅呈现`Object`中所有字段的子集。要将其与`@ResponseBody`或`ResponseEntity`控制器方法一起使用,您可以使用Jackson的`@JsonView`注解来激活序列化视图类,如下例所示
-
Java
-
Kotlin
@RestController
public class UserController {
@GetMapping("/user")
@JsonView(User.WithoutPasswordView.class)
public User getUser() {
return new User("eric", "7!jd#h23");
}
}
public class User {
public interface WithoutPasswordView {};
public interface WithPasswordView extends WithoutPasswordView {};
private String username;
private String password;
public User() {
}
public User(String username, String password) {
this.username = username;
this.password = password;
}
@JsonView(WithoutPasswordView.class)
public String getUsername() {
return this.username;
}
@JsonView(WithPasswordView.class)
public String getPassword() {
return this.password;
}
}
@RestController
class UserController {
@GetMapping("/user")
@JsonView(User.WithoutPasswordView::class)
fun getUser(): User {
return User("eric", "7!jd#h23")
}
}
class User(
@JsonView(WithoutPasswordView::class) val username: String,
@JsonView(WithPasswordView::class) val password: String
) {
interface WithoutPasswordView
interface WithPasswordView : WithoutPasswordView
}
@JsonView 允许使用一系列视图类,但是每个控制器方法只能指定一个。如果您需要激活多个视图,请使用组合接口。 |