Backend Development 8 min read

Mastering @JsonView in Spring Boot 3: Dynamic JSON Serialization Techniques

This article explains how to use Jackson's @JsonView annotation in Spring Boot 3 to flexibly control JSON output for different REST scenarios, covering basic usage, programmatic view selection, view‑based MVC responses, deserialization restrictions, and default‑inclusion configuration with practical code examples.

Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Mastering @JsonView in Spring Boot 3: Dynamic JSON Serialization Techniques

1. Introduction

In RESTful web applications, the data returned to the front‑end often varies by scenario—e.g., a user list needs only basic fields while a detail view requires all information, including sensitive data. Creating separate DTOs for each case leads to code duplication and maintenance overhead.

The @JsonView annotation from the Jackson library allows you to define multiple view classes and annotate entity fields with the view(s) in which they should be serialized, enabling dynamic field selection directly in controller methods.

2. Practical Examples

2.1 Basic Usage

Define view interfaces and annotate fields:

<code>public class User {
    public interface PublicView {}
    public interface InternalView extends PublicView {}

    @JsonView(PublicView.class)
    private Long id;
    @JsonView(PublicView.class)
    private String name;
    @JsonView(PublicView.class)
    private String address;
    @JsonView(InternalView.class)
    private String password;
    @JsonView(InternalView.class)
    private String idCard;
    @JsonView(PublicView.class)
    private String email;
    // getters & setters
}</code>

Controller returning the public view:

<code>@RestController
@RequestMapping("/users")
public class UserController {
    @JsonView(User.PublicView.class)
    @GetMapping("/query")
    public User query() {
        return new User(1L, "pack", "四川乌鲁木齐市", "123456", "152528202504096514", "[email protected]");
    }
}</code>

When the endpoint is called, only fields marked with PublicView are included in the JSON response.

2.2 Programmatic View Selection

If you prefer to set the view at runtime, wrap the return value in MappingJacksonValue and specify the view class:

<code>@GetMapping("/getUser")
public MappingJacksonValue getUser() {
    User user = new User(1L, "pack", "四川乌鲁木齐市", "123456", "152528202504096514", "[email protected]");
    MappingJacksonValue value = new MappingJacksonValue(user);
    value.setSerializationView(User.PublicView.class);
    return value;
}</code>

2.3 View‑Based MVC Response

In a traditional MVC controller you can add the view class to the model and return a MappingJackson2JsonView :

<code>@Controller
public class UserViewController {
    @GetMapping("/userview")
    public ModelAndView userView(Model model) {
        User user = new User(1L, "pack", "四川乌鲁木齐市", "123456", "152528202504096514", "[email protected]");
        model.addAttribute("user", user);
        model.addAttribute(JsonView.class.getName(), User.PublicView.class);
        return new ModelAndView(new MappingJackson2JsonView());
    }
}</code>

2.4 Restricting Deserialization

To prevent certain fields from being deserialized, read the JSON with a specific view:

<code>@PostMapping("/deserialize_json")
public User deserialize(@RequestBody String json) throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    return mapper.readerWithView(User.PublicView.class)
                 .forType(User.class)
                 .readValue(json);
}</code>

Only fields annotated with PublicView will be populated; password and idCard are ignored.

2.5 Configuring Default View Inclusion

When many fields exist, annotating each one can be tedious. By enabling the following property, fields without an explicit @JsonView are included by default:

<code>spring:
  jackson:
    mapper:
      default-view-inclusion: true</code>

After removing @JsonView from the public fields, they are still serialized, while fields that retain the InternalView annotation remain hidden unless that view is requested.

3. Summary

Using @JsonView in Spring Boot 3 provides a clean, maintainable way to tailor JSON responses and control deserialization without proliferating DTO classes. You can apply the annotation declaratively, set views programmatically, integrate with MVC, and adjust default behavior via configuration.

JavaSerializationSpring BootJacksonRESTJsonView
Spring Full-Stack Practical Cases
Written by

Spring Full-Stack Practical Cases

Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.