Jackson field annotations that ignore all properties but those that are listed
Is there a Jackson annotation for fields and / or getters that ignore all properties of a field's value except those listed?
It will look like @JsonIgnoreProperties
when applied to a field, except that instead of including all but the listed properties, it will exclude everything but the listed properties.
for example if the annotation was named @JsonIncludeProperties
:
class A {
final int a = 1;
final int b = 1;
... // final int c = 1; through final int y = 1;
final int z = 1;
}
class B {
@JsonProperty
@JsonIncludeProperties({"m", "o"})
A a1;
@JsonProperty
A a2;
}
Will be serialized for:
{
"a1": {
"m": 1,
"o": 1
},
"a2": {
"a": 1,
"b": 1,
... // "c": 1, through "y": 1,
"z": 1
}
}
+3
source to share
1 answer
You can use Jackson filters and custom annotation. Here's an example:
public class JacksonIncludeProperties {
@Retention(RetentionPolicy.RUNTIME)
@interface JsonIncludeProperties {
String[] value();
}
@JsonFilter("filter")
@JsonIncludeProperties({"a", "b1"})
static class Bean {
@JsonProperty
public final String a = "a";
@JsonProperty("b1")
public final String b = "b";
@JsonProperty
public final String c = "c";
}
private static class IncludePropertiesFilter extends SimpleBeanPropertyFilter {
@Override
protected boolean include(final PropertyWriter writer) {
final JsonIncludeProperties includeProperties =
writer.getContextAnnotation(JsonIncludeProperties.class);
if (includeProperties != null) {
return Arrays.asList(includeProperties.value()).contains(writer.getName());
}
return super.include(writer);
}
}
public static void main(String[] args) throws JsonProcessingException {
final ObjectMapper objectMapper = new ObjectMapper();
final SimpleFilterProvider filterProvider = new SimpleFilterProvider();
filterProvider.addFilter("filter", new IncludePropertiesFilter());
objectMapper.setFilters(filterProvider);
System.out.println(objectMapper.writeValueAsString(new Bean()));
}
}
+2
source to share