Jackson 序列化 Optional 与 YAML 的空值 [英] Jackson serialising Optional with null value for YAML
问题描述
目前我正在使用 YAMLFactory 进行配置ObjectMapper
序列化和反序列化 Pojos <=>YAML
,尽管尝试了 Jackson
中的常用技巧,但它在序列化中写入了 null
值.
Currently I am using the YAMLFactory to configure the ObjectMapper
to serialise and deserialise Pojos <=> YAML
, however it writes null
values in serialisation despite attempting the usual tricks in Jackson
.
在类级别或字段级别使用 @JsonInclude(JsonInclude.Include.NON_NULL)
进行注释没有影响.我还尝试使用 @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
注释类,但也没有任何影响.使用 YAMLFactory
时如何实现这一点?
Annotating with @JsonInclude(JsonInclude.Include.NON_NULL)
on the class level or the field level has no affect. I have also tried annotating classes with @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
with no affect either. How do you achieve this when using the YAMLFactory
?
我发现了一个类似的问题,但用例确实如此似乎不一样.明确地说,我试图完全省略该字段.
I have found a similar question but the use case does not appear to be the same. To be clear I am trying to omit the field altogether.
这是一个例子(我也在使用 Lombok
)
Here is an example (I am also using Lombok
)
@Data
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class QueueProperties extends Properties {
@JsonProperty("QueueName")
private String queueName;
@JsonProperty("RedrivePolicy")
private RedrivePolicy redrivePolicy;
public Optional<RedrivePolicy> getRedrivePolicy() {
return Optional.ofNullable(redrivePolicy);
}
}
序列化时:
Properties:
QueueName: 471416d1-3643-4d5a-a033-65f22757dcaf-chargeback-paypal-ingestion-ingest_dispute
RedrivePolicy: null
ObjectMapper 配置:
ObjectMapper configuration:
ObjectMapper mapper = new ObjectMapper(new YAMLFactory().enable(YAMLGenerator.Feature.MINIMIZE_QUOTES));
mapper.registerModule(new Jdk8Module());
推荐答案
getRedrivePolicy
getter 方法总是返回 not-null
对象,即使如此,Optional
可以引用 null
.在这种情况下,您应该跳过 empty
对象.Optional
和 null
被认为是空的,我们可以使用 JsonInclude.Include.NON_EMPTY
作为它.您可以在类级别保留 @JsonInclude(JsonInclude.Include.NON_NULL)
并仅为给定的 getter 添加 NON_EMPTY
:
getRedrivePolicy
getter method always returns not-null
object, even so, Optional
could reference to null
. In this case, you should skip empty
objects. Optional
with null
is considered as empty and we can use JsonInclude.Include.NON_EMPTY
for it. You can keep @JsonInclude(JsonInclude.Include.NON_NULL)
on class level and add NON_EMPTY
only for given getter:
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public Optional<Object> getRedrivePolicy() {
return Optional.ofNullable(redrivePolicy);
}
这篇关于Jackson 序列化 Optional 与 YAML 的空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!