杰克逊字段注释忽略了列出的所有属性

时间:2015-04-25 00:52:54

标签: java json jackson

是否有字段和/或getter的Jackson注释会忽略除列出的字段之外的所有字段属性?

当应用于某个字段时,它会像@JsonIgnoreProperties一样,除了不包括除列出的属性之外的所有属性,它将排除除列出的属性之外的所有属性。

例如,如果注释名为@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;
}

将序列化为:

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

2 个答案:

答案 0 :(得分:2)

您可以使用the Jackson filters和自定义注释来实现。这是一个例子:

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()));
    }
}

答案 1 :(得分:0)

如果您指的是@JsonIncludeProperties,它包含在 jackson-databind 库的 2.12 中。该问题的完整详细信息在此处https://github.com/FasterXML/jackson-databind/issues/1296。 Spring Boot 将提供 2.5.x 版本,请参见此处https://docs.spring.io/spring-boot/docs/2.5.x/reference/html/appendix-dependency-versions.html#dependency-versions