Spring boot jackson non_null 属性不起作用

问题描述 投票:0回答:3

我正在使用 Spring boot 1.5.7-RELEASE

我正在尝试在我的应用程序中设置 global non null Jackson 属性。

但它不起作用。

我在 application.properties 和 bootstrap.properties 中都尝试过,但不起作用。

spring.jackson.default-property-inclusion=NON_NULL
spring.jackson.serialization-inclusion=NON_NULL

但是当我在班级级别申请时,效果很好。

@JsonInclude(JsonInclude.NON_NULL)
spring-boot jackson
3个回答
10
投票

根据文档正确答案是:

spring.jackson.default-property-inclusion=non_null

(注意小写的 non_null - 这可能是问题的原因)

编辑: 我创建了一个简单的 Spring Boot 1.5.7.RELEASE 项目,仅包含以下两个编译依赖项:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
</dependency> 

然后我添加了以下控制器和响应类(使用 Lombok 跳过一些样板代码):

@RestController
@RequestMapping("/jackson")
public class JacksonTestController {

    @GetMapping("/test")
    public Response test() {
        val response = new Response();
        response.setField1("");

        return response;
    }
}

@Data
class Response {
    private String field1;
    private String field2;
    private Integer field3;
}

最后,我根据文档配置了 Jackson,运行应用程序,然后导航到

http://localhost:8080/jackson/test
。结果是(正如预期的那样):

{"field1":""}

之后,我深入研究了Spring Boot的源代码,发现Spring使用类

org.springframework.http.converter.json.Jackson2ObjectMapperBuilder
来创建
com.fasterxml.jackson.databind.ObjectMapper
的实例。然后,我在上述构建器类的方法
public <T extends ObjectMapper> T build()
中放置了一个断点,并在调试模式下运行我的应用程序。

我发现在应用程序启动期间创建了 8 个

ObjectMapper
实例,其中只有一个是使用
application.properties
文件内容进行配置的。 OP 从未指定他到底如何使用序列化,因此他的代码可能引用了其他 7 个可用对象映射器之一。

无论如何,确保应用程序中的所有对象映射器配置为仅序列化非空属性的唯一方法是创建自己的类副本

org.springframework.http.converter.json.Jackson2ObjectMapperBuilder
并将该选项硬编码为默认值或将类自定义为在每次调用其构造函数或构建方法期间读取
application.properties


4
投票

也许我参加聚会迟到了,但这可能对某人有帮助。

扩展 WebMvcConfigurationSupport 类并按照您想要的方式自定义 Springboot 配置。

@Configuration
public class Config extends WebMvcConfigurationSupport{

    @Override
    protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        converter.setObjectMapper(mapper);
        converters.add(converter);
        super.configureMessageConverters(converters);
    }
}

0
投票

我只是处理

application.properties
中的设置,没有采取任何一个。就我而言,我扩展了一个抽象配置类,它定义了一个具有完全不同设置的
ObjectMapper
bean。所以我必须重写它。

是什么让我找到了使用 Spring Boot 应用程序具有的

/beans
执行器端点,并搜索“
ObjectMapper
”的地方。它揭示了一个我没有意识到正在创建的实例。

© www.soinside.com 2019 - 2024. All rights reserved.