Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson JSON Filter without @JsonFilter Annotation

Tags:

java

json

jackson

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.

like image 311
Matt Avatar asked Dec 16 '14 18:12

Matt


1 Answers

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);
like image 85
StaxMan Avatar answered Sep 21 '22 15:09

StaxMan