![](/img/trans.png)
[英]Optional int parameter '' is present but cannot be translated into a null value due to being declared as a primitive type
[英]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.