Skip to content

Support for removing JSON attributes from response bodies in MVC #3777

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

raccoonback
Copy link
Contributor

Motivation

This PR adds support for filtering out specific JSON attributes from response bodies in Spring MVC, extending functionality previously available only in WebFlux.

Changes

  • Implemented a filter that removes selected JSON fields in Spring MVC responses.
  • Reused core logic from the WebFlux implementation where possible to maintain consistency.

@raccoonback raccoonback force-pushed the support-json-field-removal-filter-in-mvc branch from 736a0b8 to 5903a10 Compare April 19, 2025 15:08
Comment on lines +183 to +192
try {
JsonNode jsonBodyContent = OBJECT_MAPPER.readValue(responseBody, JsonNode.class);

removeJsonAttributes(jsonBodyContent, immutableFieldList, deleteRecursively);

responseBody = OBJECT_MAPPER.writeValueAsString(jsonBodyContent);
}
catch (JsonProcessingException exception) {
throw new IllegalStateException("Failed to process JSON of response body.", exception);
}
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove a specific attribute based on a JsonNode.


return modifyResponseBody(String.class, String.class, APPLICATION_JSON_VALUE, (request, response, body) -> {
String responseBody = body;
if (APPLICATION_JSON.isCompatibleWith(response.headers().getContentType())) {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Only process when the content-type is application/json.

Comment on lines +203 to +205
if (deleteRecursively) {
jsonNode.forEach(childNode -> removeJsonAttributes(childNode, fieldNames, true));
}
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If nested attributes also need to be removed, handle them recursively.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants