Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Black Friday 2026 – NPI EA – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

1. Overview

In this quick tutorial, we’ll show how to filter JSON serialization output depending on a user role defined in Spring Security.

2. Why Do We Need To Filter?

Let’s consider a simple yet common use case where we have a web application that serves users with different roles. For example, let these roles be User and Admin.

To begin with, let’s define a requirement that Admins have full access to the internal state of objects exposed via a public REST API. On the contrary, Users should see only a predefined set of objects’ properties.

We’ll use the Spring Security framework to prevent unauthorized access to web application resources.

Let’s define an object that we’ll return as a REST response payload in our API:

class Item {
    private int id;
    private String name;
    private String ownerName;

    // getters
}

Of course, we could’ve defined a separate data transfer object class for each role present in our application. However, this approach will introduce useless duplications or sophisticated class hierarchies to our codebase.

On the other hand, we can employ the use of the Jackson library’s JSON views feature. As we’ll see in the next section, it makes customizing JSON representation as easy as adding an annotation on a field.

3. @JsonView Annotation

The Jackson library supports defining multiple serialization/deserialization contexts by marking fields we want to include in JSON representation with the @JsonView annotation. This annotation has a required parameter of a Class type that is used to tell contexts apart.

When marking fields in our class with @JsonView, we should keep in mind that, by default, the serialization context includes all the properties that are not explicitly marked as being part of a view. In order to override this behavior, we can disable the DEFAULT_VIEW_INCLUSION mapper feature.

Firstly, let’s define a View class with some inner classes that we’ll be using as an argument for the @JsonView annotation:

class View {
    public static class User {}
    public static class Admin extends User {}
}

Next, we add @JsonView annotations to our class, making ownerName accessible to the admin role only:

@JsonView(View.User.class)
private final int id;
@JsonView(View.User.class)
private final String name;
@JsonView(View.Admin.class)
private final String ownerName;

4. How to Integrate @JsonView Annotation With Spring Security

Now, let’s add an enumeration containing all the roles and their names. After that, let’s introduce a mapping between JSON views and security roles:

enum Role {
    ROLE_USER,
    ROLE_ADMIN
}

class View {

    public static final Map<Role, Class> MAPPING = new HashMap<>();

    static {
        MAPPING.put(Role.ADMIN, Admin.class);
        MAPPING.put(Role.USER, User.class);
    }

    //...
}

Finally, we’ve come to the central point of our integration. In order to tie up JSON views and Spring Security roles, we need to define controller advice that applies to all the controller methods in our application.

And so far, the only thing we need to do is to override the beforeBodyWriteInternal method of the AbstractMappingJacksonResponseBodyAdvice class:

@RestControllerAdvice
class SecurityJsonViewControllerAdvice extends AbstractMappingJacksonResponseBodyAdvice {

    @Override
    protected void beforeBodyWriteInternal(
      MappingJacksonValue bodyContainer,
      MediaType contentType,
      MethodParameter returnType,
      ServerHttpRequest request,
      ServerHttpResponse response) {
        if (SecurityContextHolder.getContext().getAuthentication() != null
          && SecurityContextHolder.getContext().getAuthentication().getAuthorities() != null) {
            Collection<? extends GrantedAuthority> authorities
              = SecurityContextHolder.getContext().getAuthentication().getAuthorities();
            List<Class> jsonViews = authorities.stream()
              .map(GrantedAuthority::getAuthority)
              .map(AppConfig.Role::valueOf)
              .map(View.MAPPING::get)
              .collect(Collectors.toList());
            if (jsonViews.size() == 1) {
                bodyContainer.setSerializationView(jsonViews.get(0));
                return;
            }
            throw new IllegalArgumentException("Ambiguous @JsonView declaration for roles "
              + authorities.stream()
              .map(GrantedAuthority::getAuthority).collect(Collectors.joining(",")));
        }
    }
}

This way, every response from our application will go through this advice, and it’ll find the appropriate view representation according to the role mapping we have defined. Note that this approach requires us to be careful when dealing with users that have multiple roles.

5. Conclusion

In this brief tutorial, we’ve learned how to filter JSON output in a web application based on a Spring Security role.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Black Friday 2026 – NPI EA – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW