I am trying to dynamically serialize a given POJO in spring boot 2. My use case is, I have a very big model file and I want to retrieve only a subset of fields. The approach I found on the internet is using @JacksonFilter i.e annotate a POJO with @JsonFilter and use that filter name while serializing.
Below is the code sample
@JsonFilter("myfilter")
class Resource1{
String firstName;
String lastName;
Address address;
}
class Address {
String addr1;
String addr2;
String zipcode;
}
And when serializing, if I want only firstname I do this
SimpleFilterProvider filterProvider = new SimpleFilterProvider();
filterProvider.addFilter("myfilter", SimpleBeanPropertyFilter.filterOutAllExcept("firstName"));
ObjectMapper mapper = new ObjectMapper();
mapper.setFilterProvider(filterProvider);
mapper.writeValueAsString(resource1_instance); // Resource 1 instance
Now for eg I want to filter another POJO I need to declare JsonFilter for that given class and this repeats for any given POJO.
My concern is, in order to dynamically serialize only subset of fields, for every given POJO we need to add @JsonFilter("suitable_name") and serialize it.
Is there a way to declare a generic @JsonFilter and reuse it just like the inheritance concept.
If I use @JsonIgnore that would be static and fixed.
My requirement is if a model has v,w,x,y,z attributes and I request only x,y attributes at run time, a generic filter that would serialize only x,y attributes of POJO and give me back
Any suggestion on this would be of great help. Thanks in advance
For dynamic filtering of simpler use cases i wrote an addon for jackson to use antpath style filtering. It should be exactly what you search.
https://github.com/Antibrumm/jackson-antpathfilter
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With