gpt4 book ai didi

java - 覆盖全局 jackson 配置

转载 作者:行者123 更新时间:2023-11-30 01:55:10 25 4
gpt4 key购买 nike

我的应用程序 null 值不会被序列化为 json,这没问题。但在一种特定情况下,我希望将空值发送给客户端。我怎样才能做到这一点?

class User  {

private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}

对于这个类,我尝试使用 JsonInclude.Always,但其默认值稍后会在配置中被覆盖。

最佳答案

使用JsonIninclude注释。示例:

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Test {

public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(Include.NON_NULL);

System.out.println(mapper.writeValueAsString(new User()));
}
}

@JsonInclude
class User {

private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}

上面的代码打印:

{"name":null}

JsonInclude 中的默认值为 ALWAYS:

/**
* Inclusion rule to use for instances (values) of types (Classes) or
* properties annotated.
*/
public Include value() default Include.ALWAYS;

其他选项是使用 JsonSerialize 注释:

@JsonSerialize(include = Inclusion.ALWAYS)
class User {

private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}

结果与 JsonInclude 相同。

关于java - 覆盖全局 jackson 配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54782829/

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