I was trying to filter out certain fields from serialization via SimpleBeanPropertyFilter
using the following (simplified) code:
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
SimpleFilterProvider filterProvider = new SimpleFilterProvider().addFilter("test",
SimpleBeanPropertyFilter.filterOutAllExcept("data1"));
try {
String json = mapper.writer(filterProvider).writeValueAsString(new Data());
System.out.println(json); // output: {"data1":"value1","data2":"value2"}
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
private static class Data {
public String data1 = "value1";
public String data2 = "value2";
}
Us I use SimpleBeanPropertyFilter.filterOutAllExcept("data1"));
I was expecting that the created serialized Json string contains only {"data1":"value1"}
, however I get {"data1":"value1","data2":"value2"}
.
How to create a temporary writer that respects the specified filter (the ObjectMapper can not be re-configured in my case).
Note: Because of the usage scenario in my application I can only accept answers that do not use Jackson annotations.
You would normally annotate your Data
class to have the filter applied:
@JsonFilter("test")
class Data {
You have specified that you can't use annotations on the class. You could use mix-ins to avoid annotating Data
class.
@JsonFilter("test")
class DataMixIn {}
Mixins have to be specified on an ObjectMapper
and you specify you don't want to reconfigure that. In such a case, you can always copy the ObjectMapper
with its configuration and then modify the configuration of the copy. That will not affect the original ObjectMapper
used elsewhere in your code. E.g.
ObjectMapper myMapper = mapper.copy();
myMapper.addMixIn(Data.class, DataMixIn.class);
And then write with the new ObjectMapper
String json = myMapper.writer(filterProvider).writeValueAsString(new Data());
System.out.println(json); // output: {"data1":"value1"}