簡體   English   中英

如何在 Spring 引導中將請求正文中的少數屬性作為可選

[英]How to have few properties in Request Body as optional in Spring Boot

I have a REST endpoint(/users) in my controller which is of HTTP type POST, this REST endpoint accepts a RequestBody of users which has the following properties:

{
  name: 'abc',
  address: 'xyz',
  phoneNo: '123',
  age: '12',
  email: 'xyz@gmail.com'  
}

我的要求是, age應該是完全可選的,就像用戶調用 REST 端點而不在有效負載中指定age (關鍵字)一樣,它應該像一個魅力一樣工作。 例如

{
  name: 'abc',
  address: 'xyz',
  phoneNo: '123',
  email: 'xyz@gmail.com'  
}

因此,如果用戶沒有在有效負載中指定age關鍵字,我有一個默認的業務邏輯要執行,另一方面,如果用戶指定age關鍵字及其值,那么我還有一些其他邏輯要處理。

僅供參考 - 我有一個由Users創建的 DTO class 我已經聲明了所有屬性,這是它的外觀

@Data
class Users{
 @NotNull
 private String name;
 @NotNull
 private String address;
 @NotNull
 private String phoneNo;
 private String age;
 @NotNull
 private String email;  
 
}

因此,如果有人為我提供了一種處理我的問題陳述的方法,我將不勝感激。

謝謝,外星人

on the DTO class, so that if the RequestBody is not having the property then that property will be ignored.在 DTO class 上使用注釋 ,這樣如果 RequestBody 沒有該屬性,則該屬性將被忽略。

@Data
@JsonIgnoreProperties(ignoreUnknown = true)
class Users {
  .......
  .......
}

暫無
暫無

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

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