JsonInclude.NON_EMPTY 和 JsonInclude.NON_NULL 是两个 Jackson 注释,可用于控制序列化 JSON 输出中包含哪些字段。
- JsonInclude.NON_EMPTY will ignore fields whose values are empty, such as empty strings, empty collections.
- JsonInclude.NON_NULL will only ignore fields whose values are null.
如果我向 ObjectMapper 注册 JsonInclude.NON_EMPTY,那么在序列化对象时,不仅空字段而且空值都会被忽略。为什么 NON_EMPTY 会忽略空字段?
下面是代码
@Builder
class Person {
String firstName;
String middleName;
String lastName;
}
@Test
void testSerialization() {
Person person = Person()
.builder()
.firstName("test")
.middleName("")
.lastName(null)
.build();
ObjectMapper mapper1 = new ObjectMapper();
mapper1.setSerializationInclusion(Include.NON_EMPTY);
String deserializeStr1 = mapper1.writeValueAsString(person);
// deserializeStr1: { "firstName": "test" }
// why does "lastName" not present?
// why not being: { "firstName": "test", "lastName": null } ?
}
您需要添加 import com.fasterxml.jackson.annotation.JsonInclude;
它应该是 POJO 类的顶部
@JsonInclude(JsonInclude.Include.NON_NULL) | @JsonInclude(JsonIninclude.Include.NON_EMPTY)