Skip to content

Commit

Permalink
Explain how to provide serialization view programmatically
Browse files Browse the repository at this point in the history
Closes gh-25596
  • Loading branch information
rstoyanchev committed Sep 7, 2020
1 parent b6ff12d commit 94c91c9
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions src/docs/asciidoc/web/webmvc.adoc
Expand Up @@ -3403,6 +3403,39 @@ which allow rendering only a subset of all fields in an `Object`. To use it with
NOTE: `@JsonView` allows an array of view classes, but you can specify only one per
controller method. If you need to activate multiple views, you can use a composite interface.

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",role="primary"]
.Java
----
@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;
}
}
----
[source,kotlin,indent=0,subs="verbatim,quotes",role="secondary"]
.Kotlin
----
@RestController
class UserController {
@GetMapping("/user")
fun getUser(): MappingJacksonValue {
val value = MappingJacksonValue(User("eric", "7!jd#h23"))
value.serializationView = User.WithoutPasswordView::class.java
return value
}
}
----

For controllers that rely on view resolution, you can add the serialization view class
to the model, as the following example shows:

Expand Down

0 comments on commit 94c91c9

Please sign in to comment.