【问题标题】:How to configure jackson non null globally in Spring Boot 1.5.9如何在 Spring Boot 1.5.9 中全局配置 jackson non null
【发布时间】:2018-04-23 20:58:25
【问题描述】:

我使用的是 Spring Boot 1.5.9 和 jackson 2.8.10。我想全局配置这个@JsonInclude(Include.NON_EMPTY)注解,以便我的API的所有对象都按照注解的规则进行序列化。

我怎样才能得到这个?

我试图通过application.properties文件

spring.jackson.default-property-inclusion=non_null

也可以通过一个配置类:

@Primary
    @Bean
    public Jackson2ObjectMapperBuilder objectMapperBuilder() {
        Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
        builder.serializationInclusion(JsonInclude.Include.NON_NULL);
        builder.serializationInclusion(JsonInclude.Include.NON_EMPTY);
        builder.failOnUnknownProperties(false);
        return builder;
    }

但是这些都没有效果。它不起作用

有人知道怎么做吗?

【问题讨论】:

    标签: java spring spring-boot jackson


    【解决方案1】:

    使用spring.jackson.default-property-inclusion=non_null 属性是最好的方法,因为它会被Jackson2ObjectMapperBuilder 对象选中。这应该确保它将被应用到任何地方。

    此方法适用于 2.0.0。我测试了 1.5.9、1.5.10 和 1.5.11 和 1.5.12,但它们都没有使用简单的测试,例如:

    @Autowired 
    private ObjectMapper objectMapper;
    
    @Test
    public void shouldOutputEmpty() {
      Map<String, Object> obj = new HashMap<>();
      obj.put("a", null);
      String result = objectMapper.writeValueAsString(obj);
      assertThat(result).isEqualTo("{}");
    }
    

    这很奇怪,因为Appendix A mentions this property。一种解决方法是将 Jackson 更新到 2.9.X(Spring Boot 2.0.0 使用 2.9.4):

    dependencyManagement {
      dependencies {
        dependency 'com.fasterxml.jackson.core:jackson-core:2.9.4'
        dependency 'com.fasterxml.jackson.core:jackson-databind:2.9.4'
        dependency 'com.fasterxml.jackson.core:jackson-annotations:2.9.4'
      }
    }
    

    【讨论】:

    • 那你有什么建议呢?将我的 pom 文件更改为 Spring Boot 2.0.0 版本
    • @AlejoDev 更新到 Jackson 2.9 是解决它的一种方法。我不会深入研究它,但它可能是Issue #1522
    • 我在哪里支付你告诉我的,我找不到在哪里。我正在使用 Maven
    • 在 Maven (pom.xml) 或 Gradle (build.gradle) 项目配置中,您需要使用 2.9 jackson 依赖项。我的例子是 Gradle。
    猜你喜欢
    • 2016-04-09
    • 2017-11-18
    • 2016-01-28
    • 1970-01-01
    • 2019-04-01
    • 2018-06-13
    • 1970-01-01
    • 1970-01-01
    • 2018-11-04
    相关资源
    最近更新 更多