根据第三方 API 规范,如果不存在任何值,我需要使用 ObjectMapper
在 JSON 中发送空值,
预期结果:“可选”:null
如果可选值存在,则发送"optional": "value"
我在 Jackson – Working with Maps and nulls 中没有找到这样的选项
代码:
requestVO = new RequestVO(optional);
ObjectMapper mapper = new ObjectMapper();
String requestString = mapper.writeValueAsString(requestVO);
类:
public class RequestVO {
String optional;
public RequestVO(String optional) {
this.optional = optional;
}
public String getOptional() {
return optional;
}
public void setOptional(String optional) {
this.optional= optional;
}
最佳答案
将 @JsonInclude(JsonInclude.Include.USE_DEFAULTS)
注释添加到您的类中。
@JsonInclude(JsonInclude.Include.USE_DEFAULTS)
class RequestVO {
String optional;
public RequestVO(String optional) {
this.optional = optional;
}
public String getOptional() {
return optional;
}
public void setOptional(String optional) {
this.optional = optional;
}
}
示例:
RequestVO requestVO = new RequestVO(null);
ObjectMapper mapper = new ObjectMapper();
try {
String requestString = mapper.writeValueAsString(requestVO);
System.out.println(requestString);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
输出:
{"optional":null}
具有值(value):
RequestVO requestVO = new RequestVO("test");
ObjectMapper mapper = new ObjectMapper();
try {
String requestString = mapper.writeValueAsString(requestVO);
System.out.println(requestString);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
输出:
{"optional":"test"}
您可以在偶数属性上使用 @JsonInclude
注释。因此,通过这种方式,您可以序列化为 null 或在序列化时忽略某些属性。
关于java - ObjectMapper - 如何在 JSON 中发送空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53801381/