Reputation: 1583
I'm trying to implement wrapper class, that will be serialized by Jackson with omitting fields depending on runtime configuration:
class Partial<T> {
T value;
List<String> fieldsToSkip;
}
This
class Example{int a=1; int b=2; int c=3;}
new Partial(new Example(), asList("b"));
suppose to be serialized to {"a":1, "c":3}
.
@JsonUnwrapped
with @JsonFilter
seems to be right approach here. The problem is that the filter works on value
field level, where there's no access to host Partial
instance.
What is the best way to implement such thing?
Upvotes: 1
Views: 793
Reputation: 22224
You can create at run time an ObjectWriter
with a filter also defined at run time and use it to write the value in Partial
:
SimpleBeanPropertyFilter filter =
SimpleBeanPropertyFilter.serializeAllExcept(new HashSet<>(partial.fieldsToSkip));
FilterProvider fp = new SimpleFilterProvider().addFilter("exampleFilter", filter);
String text = objectMapper.writer(fp).writeValueAsString(partial.value);
and tell Jackson that this filter should be applied to Example
class:
@JsonFilter("exampleFilter")
class Example{int a=1; int b=2; int c=3;}
You may want to change fieldsToSkip
to a Set<String>
Upvotes: 1