Unlock the Power of Spring Boot’s @JsonView for Flexible API Serialization
This guide explains how to use Jackson's @JsonView annotation in Spring Boot to define view interfaces, annotate entity fields, configure controller methods, handle dynamic view selection, and apply best‑practice settings for secure and efficient JSON responses.
Define View Interfaces
Create empty marker interfaces to represent different serialization views. For example:
public class Views {
// Basic view
public interface Public {}
// Internal view extends the basic view to include its fields
public interface Internal extends Public {}
}Apply @JsonView in Entity Classes
Annotate fields or getters with the desired view. Only fields marked with a view will be serialized when that view is active.
public class User {
@JsonView(Views.Public.class)
private Long id;
@JsonView(Views.Public.class)
private String username;
@JsonView(Views.Internal.class)
private String email;
@JsonView(Views.Internal.class)
private String password;
// constructors, getters, setters omitted for brevity
}Use @JsonView in Controllers
Specify the view on controller methods to control which fields are returned for each endpoint.
@RestController
@RequestMapping("/api/users")
public class UserController {
@GetMapping("/public")
@JsonView(Views.Public.class) // only Public fields
public List<User> getUsersPublic() {
return userService.findAll();
}
@GetMapping("/internal")
@JsonView(Views.Internal.class) // Public + Internal fields
public List<User> getUsersInternal() {
return userService.findAll();
}
}Test Results
Running the application and calling the endpoints yields different JSON outputs:
GET /api/users/public returns:
[
{"id":1,"username":"john_doe"},
{"id":2,"username":"jane_doe"}
]GET /api/users/internal returns:
[
{"id":1,"username":"john_doe","email":"[email protected]","password":"encryptedPassword123"},
{"id":2,"username":"jane_doe","email":"[email protected]","password":"encryptedPassword456"}
]Because the Internal view extends Public, the id and username fields appear in both responses.
Class‑Level @JsonView
Since Jackson 2.9, you can place @JsonView on a class to set a default view for all fields that lack an explicit annotation.
@JsonView(Views.Public.class)
public class Product {
private Long id; // behaves as if annotated with Public
private String name; // behaves as if annotated with Public
@JsonView(Views.Internal.class)
private BigDecimal costPrice; // only Internal view serializes this field
}Dynamic View Selection
When the view must be chosen at runtime, wrap the response in MappingJacksonValue and set the serialization view conditionally.
import org.springframework.http.converter.json.MappingJacksonValue;
@RestController
@RequestMapping("/api/dynamic")
public class DynamicViewController {
@GetMapping("/user")
public MappingJacksonValue getUserDynamic(@RequestParam boolean includeSensitive) {
User user = userService.findUserById(1L);
MappingJacksonValue wrapper = new MappingJacksonValue(user);
if (includeSensitive) {
wrapper.setSerializationView(Views.Internal.class);
} else {
wrapper.setSerializationView(Views.Public.class);
}
return wrapper;
}
}Calling /api/dynamic/user?includeSensitive=true includes sensitive fields; setting the flag to false omits them.
Configure Default View Inclusion
By default, only fields explicitly annotated with @JsonView are serialized. To include unannotated fields in every view, set the following property:
# Enable default view inclusion
spring.jackson.mapper.default-view-inclusion=trueBest Practices & Common Issues
API Design : Define clear view interfaces for different API scenarios such as public data, internal details, or admin views.
Leverage Inheritance : Use interface inheritance to reuse fields across views and extend them when needed.
Avoid Annotation Conflicts : When generating OpenAPI documentation with SpringDoc, the
@ApiResponse implementationattribute may override @JsonView filtering. Adjust the documentation generation if the response schema appears inaccurate.
Performance : Returning only necessary fields reduces payload size and improves network performance.
Security : @JsonView helps prevent accidental exposure of sensitive data such as passwords or internal identifiers.
Overall, @JsonView provides a flexible, declarative way to control JSON serialization, making it ideal for APIs that need to serve data at varying levels of granularity.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Senior Xiao Ying
Dedicated to sharing Java backend technical experience and original tutorials, offering career transition advice and resume editing. Recognized as a rising star in CSDN's Java backend community and ranked Top 3 in the 2022 New Star Program for Java backend.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
