簡體   English   中英

不存在的可選字段與在休息請求正文中存在空值的字段之間的區別

[英]Difference between an optional field not being present Vs field present with null value in rest request body

有沒有辦法檢查請求正文中是否存在具有空值的可選字段,或者它根本不存在於請求正文中。 我有一個要求,如果一個可選字段存在且值設置為 null,我們需要一個異常,但如果該字段根本不存在,則認為可以。

在下面的示例中 operatorName 是一個可選字段:

Invalid Case:
{
    "creationDateTime": "2019-10-08",
    "requestedAmount": "2499",
    "operatorPhone": "1234567890",
    "operatorName": null 
}

Valid Case:

{
    "creationDateTime": "2019-10-08",
    "requestedAmount": "2499",
    "operatorPhone": "1234567890"
}

請建議是否有辦法知道請求中是否存在 operatorName。 默認情況下,Java 將值設置為 null 是字段不存在。

您可以使用@JsonInclude(JsonInclude.Include.NON_NULL)

如果您使用類來映射請求,默認情況下,Java 會將值設置為 null,如果字段不存在。

您可以使用Map來獲取請求數據而不是類並檢查密鑰,

@PostMapping(value = "/process", consumes = APPLICATION_JSON_VALUE)
public ResponseEntity<String> process(@RequestBody Map data, HttpServletRequest request) throws IOException {
    if (data.containsKey("operatorName") && null == data.get("operatorName"))
        return ResponseEntity.badRequest().body("operatorName can not be null");
    //valid process
    return ResponseEntity.ok("success");
}

在 Model/Dto 中的operatorName上方添加@NotNull

暫無
暫無

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

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