'Spring boot Webflux - WebFilter to modify response body that returns JSON

I need to remove a few properties from the response body that returns JSON.

I have controllers like this:

   @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    Mono<**JsonNode**> test(@RequestBody JSONObject input) {
        return service.test(input);
    }

JsonNode contains

   {
       "property1" : "abc",
       "property2" : {
         "password" : "temp"
       }
   }

In response I need to remove property "property2", It should contain the below JSON before sending it to the client.

   {
       "property1" : "abc"
   }

I need to do this for all APIs. How can I write a filter for this?

@Component
public class ExampleWebFilter implements WebFilter {
 
    @Override
    public Mono<Void> filter(ServerWebExchange serverWebExchange, 
      WebFilterChain webFilterChain) {
        
        //Modify here
        return webFilterChain.filter(serverWebExchange);
    }
}

Or any other solutions?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source