为什么使用 JsonInclude.NON_EMPTY 的 ObjectMapper 序列化也会删除空字段?

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

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 } ?
}
java serialization objectmapper
1个回答
0
投票

您需要添加 import com.fasterxml.jackson.annotation.JsonInclude;

它应该是 POJO 类的顶部

@JsonInclude(JsonInclude.Include.NON_NULL) | @JsonInclude(JsonIninclude.Include.NON_EMPTY)

可能是来自 如何告诉 Jackson 在序列化期间忽略字段(如果其值为空)的重复问题?

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