簡體   English   中英

ObjectMapper - 如何在JSON中發送空值

[英]ObjectMapper - How to send null value in JSON

根據第三方API規范,如果不存在值,我需要使用ObjectMapper在JSON中發送空值,

預期結果: "optional": null

如果存在可選值,則發送"optional": "value"

我沒有在傑克遜找到這樣的選項- 使用地圖和空值

碼:

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}

有價值:

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

為混亂道歉。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM