gpt4 book ai didi

spring-boot - Spring Boot jackson non_null 属性不起作用

转载 作者:行者123 更新时间:2023-12-04 02:58:46 26 4
gpt4 key购买 nike

我正在使用 Spring Boot 1.5.7-发布 .

我正在尝试设置 全局非空 我的应用程序中的 Jackson 属性。

但它不起作用。

我在 application.properties 和 bootstrap.properties 中都尝试过,但没有工作。

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

但是当我在类里面申请时,它工作正常。
@JsonInclude(JsonInclude.NON_NULL)

最佳答案

根据documentation正确答案是:

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>

然后我添加了以下 Controller 和响应类(使用 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() 中放置了一个断点前面提到的构建器类并在 Debug模式下运行我的应用程序。

我发现 ObjectMapper 有 8 个实例在应用程序启动期间创建,其中只有一个使用 application.properties 的内容进行配置文件。 OP 从未指定他使用序列化的确切方式,因此他的代码可能引用了其他 7 个可用的对象映射器之一。

无论如何,确保应用程序中的所有对象映射器都配置为仅序列化非空属性的唯一方法是创建自己的类 org.springframework.http.converter.json.Jackson2ObjectMapperBuilder 副本。并将该选项硬编码为默认值或自定义类以读取 application.properties在每次调用它的构造函数或构建方法期间。

关于spring-boot - Spring Boot jackson non_null 属性不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51261809/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com