gpt4 book ai didi

java - 在运行时设置序列化属性

转载 作者:行者123 更新时间:2023-12-02 03:12:36 25 4
gpt4 key购买 nike

在序列化 MyObject 时,我想在运行时决定在 Attributes 类中包含或不包含 null 属性。最好的方法是什么?

import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;

@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class MyObject {
private String property1;
private DateTime property2;
private Attributes attributes;
}

@Data
public class Attributes {
private String property1;
private String property2;
}

最佳答案

如果您使用的是 Jackson 2.8,则可以使用新的“配置覆盖”功能(在高层讨论过 f.ex here )来指定等效的注释,如下所示:

mapper.configOverride(Attributes.class)
// first value for value itself (POJO); second value only relevant
// for structured types like Map/Collection/array/Optional
.setInclude(JsonInclude.Value.construct(Include.NON_NULL, null));

(以及以前只能使用注释使用的其他一些方面)

但请注意,与注释一样,此设置在初始设置后无法更改:必须为 ObjectMapper 定义一次,进一步的更改不会生效。如果您需要不同配置的映射器,则需要创建不同的实例。

关于java - 在运行时设置序列化属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40819319/

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