Skip to content

Commit 94c91c9

Browse files
committed
Explain how to provide serialization view programmatically
Closes gh-25596
1 parent b6ff12d commit 94c91c9

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

src/docs/asciidoc/web/webmvc.adoc

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3403,6 +3403,39 @@ which allow rendering only a subset of all fields in an `Object`. To use it with
34033403
NOTE: `@JsonView` allows an array of view classes, but you can specify only one per
34043404
controller method. If you need to activate multiple views, you can use a composite interface.
34053405

3406+
If you want to do the above programmatically, instead of declaring an `@JsonView` annotation,
3407+
wrap the return value with `MappingJacksonValue` and use it to supply the serialization view:
3408+
3409+
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
3410+
.Java
3411+
----
3412+
@RestController
3413+
public class UserController {
3414+
3415+
@GetMapping("/user")
3416+
public MappingJacksonValue getUser() {
3417+
User user = new User("eric", "7!jd#h23");
3418+
MappingJacksonValue value = new MappingJacksonValue(user);
3419+
value.setSerializationView(User.WithoutPasswordView.class);
3420+
return value;
3421+
}
3422+
}
3423+
----
3424+
[source,kotlin,indent=0,subs="verbatim,quotes",role="secondary"]
3425+
.Kotlin
3426+
----
3427+
@RestController
3428+
class UserController {
3429+
3430+
@GetMapping("/user")
3431+
fun getUser(): MappingJacksonValue {
3432+
val value = MappingJacksonValue(User("eric", "7!jd#h23"))
3433+
value.serializationView = User.WithoutPasswordView::class.java
3434+
return value
3435+
}
3436+
}
3437+
----
3438+
34063439
For controllers that rely on view resolution, you can add the serialization view class
34073440
to the model, as the following example shows:
34083441

0 commit comments

Comments
 (0)