gpt4 book ai didi

java - Jackson 序列化 - 忽略不设置的值,但提供显式设置为 null 的值

转载 作者:行者123 更新时间:2023-12-01 16:15:28 30 4
gpt4 key购买 nike

在我的 Spring Boot REST 应用程序中,我确实希望实现类的属性在未显式设置时应被 Jackson 忽略。但如果它们设置为null,则应提供并序列化它们。

@JsonInclude(Include.NON_NULL) 忽略 null 值,但实际未设置的值和已显式设置为 null 的值之间没有区别>.

检查以下示例(使用 Lombok),它显示了我想要在这里实现的目标:

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;

@Getter
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Example {
@JsonProperty("name")
private String name;

@JsonProperty("test")
private String test;
}

Example.builder().test("test").build() 应该产生 {test: "test"}
Example.builder().name(null).test("test).build() 应该导致 {name: NULL, test: "test"}

实现这一目标的最佳方法是什么?

最佳答案

这可以使用可选字段来实现:

public class JsonTest {
@JsonInclude(JsonInclude.Include.NON_NULL)
@Getter
@AllArgsConstructor
@NoArgsConstructor
@Builder
static class Example {
private Optional<String> name;
private Optional<String> test;
}

public static void main(String[] args) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper().registerModule(new Jdk8Module());

Example[] examples = {
new Example(),
Example.builder().name(Optional.of("exampleName")).build(),
Example.builder().name(Optional.of("exampleName")).test(Optional.empty()).build(),
};

for (Example ex : examples) {
System.out.println(mapper.writeValueAsString(ex));
}
}
}

输出:

{}
{"name":"exampleName"}
{"name":"exampleName","test":null}

关于java - Jackson 序列化 - 忽略不设置的值,但提供显式设置为 null 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62404624/

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