Matt
Matt

Reputation: 211

Jackson JSON Filter without @JsonFilter Annotation

I'm trying to filter the response of an API Endpoint using the Jackson library.

I can use @JsonFilter("[filterNameHere]") but this ends up with the class expecting the filter to be applied every time.

Is there a way I can filter the response only on one particular instance?

Pizza pizza = pizzaService.getPizzaById(pizzaId);

ObjectMapper mapper = new ObjectMapper();
FilterProvider filters = new SimpleFilterProvider().addFilter("baseFilter", SimpleBeanPropertyFilter.serializeAllExcept("base"));

String json = mapper.writer(filters).writeValueAsString(pizza);

return Response.status(200).entity(json).build();

I've tried looking around but haven't been able to find anything right.

Upvotes: 12

Views: 13431

Answers (1)

StaxMan
StaxMan

Reputation: 116522

Unfortunately association between filter id and class is static, so any class either has it or does not; that is, you can not sometimes have a filter, other times not.

It should be however possible to either:

  • indicate a "default" filter to use (with SimpleFilterProvider.setDefaultFilter()), to be used in case there is no explicitly registered filter matching the id. This filter could basically be "include all" filter, which would have no effect on processing.
  • indicate that in case no match is found for filter id, no filtering is done: SimpleFilterProvider.setFailOnUnknownId(false) (on provider instance)

So I think what you really want to do is second option, something like:

SimpleFilterProvider filters = new SimpleFilterProvider();
filters.setFailOnUnknownId(false);
String json = mapper.writer(filters).writeValueAsString(pizza);

Upvotes: 8

Related Questions