![](/img/trans.png)
[英]In Spring, can I make a single field in @RequestBody optional?
[英]How can I set an optional RequestBody field without it being deleted when I make the call?
我在 spring-boot 中有一個小程序,它通過帶有 @RequestBody 的 get 調用返回一條包含所有規格的消息(以我的汽車為例)
public class CarsRequest implements Serializable {
private String name;
private String plate ;
private String price;
}
我希望能夠確保如果一個字段設置為 null,它仍然可以找到具有值的其他字段的相關消息,在我的例子中,我想把“名稱”字段放在RequestBody,是否可以這樣做? 我試過設置
public CarsResponse getCars(@RequestBody (required = false) CarsRequest request) throws IOException {
//some code
}
但是當我 go 執行獲取時,它在獲取時完全刪除了 null 字段,因此無法執行
只需從 function 中刪除@RequestBody
注釋並保持原樣
public CarsResponse getCars(CarsRequest request) throws IOException {
//some code
}
現在所有字段都將轉換為查詢參數並且都是可選的,因為按照慣例查詢參數是可選的
public class CarsRequest implements Serializable {
private String name;
private String plate ;
private String price;
}
像這樣打電話
GET /someEndpoint?name=<value>&plate=null
但是,如果您想強制某些參數,請使用javax.annotations
或自己應用驗證。
EDIT: As asked in comment, if you are accepting JSON as parameter body then you can do one thing, you can accept it as String and then convert json to object inside function body
public CarsResponse getCars(@RequestParam(required = false) String request) throws IOException {
ObjectMapper mapper = new ObjectMapper();
CarRequest request = mapper.readValue(request,CarRequest.class);
// other code
}
並稱它為這樣
GET /someEndpoint?request="{ \"name\" : null, \"plate\": \"someValue\" }"
編輯2:
如果您想繼續發送 json 並將其轉換為 object,您可以再做一件事,您可以聲明一個類似這樣的活頁夾
// Some controller class
class SomeController {
@Autowired
ObjectMapper mapper;
// Ommited methods here
@GetMapping("/carRequest")
public ResponseEntity<String> testBinder(@RequestParam CarRequest request) {
return ResponseEntity.ok("{\"success\": \"" + request.name+ "\"}");
}
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(CarRequest.class, new CarRequestEditor(mapper));
}
static class CarRequestEditor extends PropertyEditorSupport {
private ObjectMapper objectMapper;
public CarRequestEditor(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
@Override
public void setAsText(String text) throws IllegalArgumentException
{
if (StringUtils.isEmpty(text)) {
setValue(new CarRequest());
} else {
try {
setValue(objectMapper.readValue(text, CarRequest.class));
} catch (JsonProcessingException e) {
throw new IllegalArgumentException(e);
}
}
}
}
}
請注意,客戶端需要發送這樣編碼的 json URL
http://localhost:8180/carRequest?request=%7B%22name%22%3"test"%7D
嗨,您正在使用 @RequestBody (required = false) CarsRequest,這意味着您的 CarsRequest object 本身是可選的,而不是您可以使用
@NotEmpty
private String plate ;
@NotEmpty
private String price;
您可以通過將單個字段設為 Optional 來使其成為Optional
字段,在您的情況下為Optional<String>
。 如果該字段沒有出現在請求正文中,則Optional
將為空。
public class CarsRequest implements Serializable {
private String name;
private String plate;
private Optional<String> price;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.