java / intermediate
Snippet
Dynamic JSON Filtering using @JsonView
@JsonView allows you to control which fields of an object are serialized into JSON depending on the context. You can define marker interfaces to create 'views' (e.g., Public vs. Admin) and apply them to both the data model and the controller method.
snippet.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Views {public interface Public {}public interface Internal extends Public {}}public class User {@JsonView(Views.Public.class) private String username;@JsonView(Views.Internal.class) private String email;}@RestControllerpublic class UserController {@GetMapping("/public/user")@JsonView(Views.Public.class)}
spring
Breakdown
1
interface Internal extends Public
Inheritance allows the Internal view to include all fields marked as Public.
2
@JsonView(Views.Public.class)
Indicates that the annotated field or method should only use fields associated with this view.
3
@RestController
Combined with @JsonView, Spring will filter the response body before sending it.