Sjvino User333
Sjvino User333

Reputation: 183

JsonFilter throws error "no FilterProvider configured for id"

In a webservice developed in Spring Boot framework, I am looking for a way to filter few sensitive fields in the response. I am trying with JsonFilter. Here is the code I tried so far:

@ApiModel (value = "Customer")
@JsonInclude (JsonInclude.Include.NON_NULL)
@JsonFilter("CustomerFilter")
public class Customer implements Serializable
{
...
}

Controller code that sends filtered response:

MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(customer);
FilterProvider filters = new 
  SimpleFilterProvider().setFailOnUnknownId(false).addFilter("CustomerFilter", 
  SimpleBeanPropertyFilter.filterOutAllExcept("customerId"));        
mappingJacksonValue.setFilters(filters);
return ResponseEntity.status(HttpStatus.OK).body(mappingJacksonValue);

While invoking the request, the following exception is thrown. com.fasterxml.jackson.databind.JsonMappingException: Can not resolve PropertyFilter with id 'CustomerFilter'; no FilterProvider configured

Am I missing any configuration?

Upvotes: 2

Views: 9724

Answers (2)

abhinav kumar
abhinav kumar

Reputation: 1803

Avoid using MappingJacksonValue as it fails in object chaining and provide error like ["data"]->org.springframework.http.converter.json.MappingJacksonValue["value"]->java.util.ArrayList[0])

Note : Use ObjectMapper and ObjectWriter instead of MappingJacksonValue

Try the below code snippet

        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        FilterProvider filters = new SimpleFilterProvider().setFailOnUnknownId(false).addFilter("CustomerFilter",
                SimpleBeanPropertyFilter.filterOutAllExcept("customerId"));
        ObjectWriter writer = mapper.writer(filters);
        String writeValueAsString = writer.writeValueAsString(customer);
        Customer resultCustomer = mapper.readValue(writeValueAsString, Customer.class);
        return ResponseEntity.status(HttpStatus.OK).body(resultCustomer);

Upvotes: 0

SteveDavidMusic
SteveDavidMusic

Reputation: 21

I was having the same issue this week, just resolved it now by creating a FilterConfiguration class in my config folder.

@JsonFilter("studentFilter")
public class Student {
    String name;
    String password;

    public Student() {
        this.name = "Steve";
        this.password = "superSecretPassword";
    }
}


@Configuration
public class FilterConfiguration {
    public FilterConfiguration (ObjectMapper objectMapper) {
        SimpleFilterProvider simpleFilterProvider = new SimpleFilterProvider().setFailOnUnknownId(true);
        simpleFilterProvider.addFilter("studentFilter", SimpleBeanPropertyFilter.filterOutAllExcept("name"));

        objectMapper.setFilterProvider(simpleFilterProvider);
    }
}

When I create a new Student, the password is filtered out.

Upvotes: 2

Related Questions