XDR
XDR

Reputation: 4470

Jackson field annotation that ignores all properties but those listed

Is there a Jackson annotation for fields and/or getters that ignores all properties of the value of the field except for those listed?

It would be like @JsonIgnoreProperties when applied to a field, except that instead of including all but the listed properties, it would exclude all but the listed properties.

e.g., if the annotation were 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;
}

Would serialize to:

{
    "a1": {
        "m": 1,
        "o": 1
    },
    "a2": {
        "a": 1,
        "b": 1,
        ... // "c": 1, through "y": 1,
        "z": 1
    }
}

Upvotes: 4

Views: 3397

Answers (2)

nomadus
nomadus

Reputation: 909

If you meant @JsonIncludeProperties, it is included in 2.12 of jackson-databind library. Full details of the issue are here https://github.com/FasterXML/jackson-databind/issues/1296. With spring boot it will be available with 2.5.x version see here https://docs.spring.io/spring-boot/docs/2.5.x/reference/html/appendix-dependency-versions.html#dependency-versions

Upvotes: 2

Alexey Gavrilov
Alexey Gavrilov

Reputation: 10853

You can achieve using the Jackson filters and a custom annotation. Here is 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()));
    }
}

Upvotes: 2

Related Questions