Jackson JSON

Spring 为 Jackson JSON 库提供支持。

JSON Views

Spring MVC 为 Jackson 的序列化视图 提供内置支持,它仅允许在 Object 中呈现所有字段的一个子集。要将它与 @ResponseBodyResponseEntity 控制器方法结合使用,您可以使用 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("eric", "7!jd#h23")
}

class User(
		@JsonView(WithoutPasswordView::class) val username: String,
		@JsonView(WithPasswordView::class) val password: String) {

	interface WithoutPasswordView
	interface WithPasswordView : WithoutPasswordView
}

@JsonView 允许视图类的数组,但每个控制器方法只能指定一个。如果需要激活多个视图,可以使用复合接口。

如果您希望以编程方式进行上述操作,而不是声明 @JsonView 注解,请使用 MappingJacksonValue 包装返回值并使用它来提供序列化视图:

  • Java

  • Kotlin

@RestController
public class UserController {

	@GetMapping("/user")
	public MappingJacksonValue getUser() {
		User user = new User("eric", "7!jd#h23");
		MappingJacksonValue value = new MappingJacksonValue(user);
		value.setSerializationView(User.WithoutPasswordView.class);
		return value;
	}
}
@RestController
class UserController {

	@GetMapping("/user")
	fun getUser(): MappingJacksonValue {
		val value = MappingJacksonValue(User("eric", "7!jd#h23"))
		value.serializationView = User.WithoutPasswordView::class.java
		return value
	}
}

对于依赖视图解析的控制器,您可以将序列化视图类添加到模型中,如下例所示:

  • Java

  • Kotlin

@Controller
public class UserController extends AbstractController {

	@GetMapping("/user")
	public String getUser(Model model) {
		model.addAttribute("user", new User("eric", "7!jd#h23"));
		model.addAttribute(JsonView.class.getName(), User.WithoutPasswordView.class);
		return "userView";
	}
}
@Controller
class UserController : AbstractController() {

	@GetMapping("/user")
	fun getUser(model: Model): String {
		model["user"] = User("eric", "7!jd#h23")
		model[JsonView::class.qualifiedName] = User.WithoutPasswordView::class.java
		return "userView"
	}
}