ObjectMapper - 如何在 JSON 中发送空值

ObjectMapper - How to send null value in JSON

根据第三方 API 规范,如果不存在任何值,我需要使用 ObjectMapper 在 JSON 中发送空值,

预期结果:"optional": null

如果可选值存在,则发送"optional": "value"

我在Jackson – Working with Maps and nulls

中没有找到这样的选项

代码:

requestVO = new RequestVO(optional);
ObjectMapper mapper = new ObjectMapper();
String requestString = mapper.writeValueAsString(requestVO);

Class:

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;
}

为您的 class 添加 @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}

价值:

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 或在序列化时忽略某些属性。

您可以这样配置您的 ObjectMapper:

ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

如果 JSON 请求中没有任何值,您处理的请求将如您预期的那样 null

如果需要,您甚至可以为 ObjectMapper 配置一个 Spring bean。

编辑:

我误解了这个问题,他对 JSON 响应感兴趣,而不是对解析的对象感兴趣。 本例中正确的属性是JsonInclude.Include.USE_DEFAULTS

对造成的混乱表示歉意。