Explain how to provide serialization view programmatically

Closes gh-25596
This commit is contained in:
Rossen Stoyanchev
2020-09-07 21:17:12 +01:00
parent ca6ac8e310
commit 1f3f9b1272

View File

@@ -2638,6 +2638,25 @@ which allows rendering only a subset of all fields in an Object. To use it with
controller method. Use a composite interface if you need to activate multiple views.
====
If you want to do the above programmatically, instead of declaring an `@JsonView` annotation,
wrap the return value with `MappingJacksonValue` and use it to supply the serialization view:
[source,java,indent=0]
[subs="verbatim,quotes"]
----
@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;
}
}
----
For controllers relying on view resolution, simply add the serialization view class
to the model: