From 1f3f9b1272791999ac14e6a65fe443862ca20394 Mon Sep 17 00:00:00 2001 From: Rossen Stoyanchev Date: Mon, 7 Sep 2020 21:17:12 +0100 Subject: [PATCH] Explain how to provide serialization view programmatically Closes gh-25596 --- src/docs/asciidoc/web/webmvc.adoc | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/src/docs/asciidoc/web/webmvc.adoc b/src/docs/asciidoc/web/webmvc.adoc index efce2b49becc..c20dc2009150 100644 --- a/src/docs/asciidoc/web/webmvc.adoc +++ b/src/docs/asciidoc/web/webmvc.adoc @@ -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: