gpt4 book ai didi

java - 从 ObjectMapper 中的 POJO 覆盖 @JsonInclude(Include.NON_NULL)

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:34:38 27 4
gpt4 key购买 nike

问题: 是否可以在创建 ObjectMapper 时覆盖 POJO 中定义的 Include.NON_NULL

解释:

假设我有一个如下所示的 POJO:

@JsonInclude(Include.NON_NULL)
class POJO {
String name;
String description;
//Constructors, Getters & Setters, etc
}

还有一个测试类如下:

class Main {
public static void main(String args[]) {
POJO p = new POJO();
ObjectMapper mapper = new ObjectMapper();
String jsonString = mapper.setSerializationInclusion(Include.ALWAYS)
.writerWithDefaultPrettyPrinter()
.writeValueAsString(p);
//jsonString should contain empty name & description fields, but they doesn't
}
}

最佳答案

您可以使用混合,因为它优先于注释。

@JsonInclude(JsonInclude.Include.ALWAYS)
public class MixIn {
}

并将其添加到映射器

ObjectMapper mapper = new ObjectMapper();
mapper.addMixIn(POJO.class, MixIn.class);

结果会是

{"name":null,"description":null}

关于java - 从 ObjectMapper 中的 POJO 覆盖 @JsonInclude(Include.NON_NULL),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45571979/

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