0

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'  
}

My requirement is such that, the age should be completely optional, as in if the user invokes the REST endpoint without specifying the age(keyword) in the payload it should work like a charm. For e.g.

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

So, if in case the user doesn't specify age keyword in the payload I have a default business logic to execute, on the other hand, if the user specifies age keyword along with its value then I have some other logic to process.

FYI - I have a DTO class created of Users where I've declared all the properties, here's how it looks

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

So I kindly appreciate it if someone provides me with a way to handle my problem statement.

Thanks, Aliens!

nickgkd
  • 35
  • 7
  • Does this answer your question? [How to ignore "null" or empty properties in json, globally, using Spring configuration](https://stackoverflow.com/questions/38828536/how-to-ignore-null-or-empty-properties-in-json-globally-using-spring-configu) – akop Jul 27 '22 at 16:16

1 Answers1

2

Use the annotation @JsonIgnoreProperties(ignoreUnknown = true) on the DTO class, so that if the RequestBody is not having the property then that property will be ignored.

@Data
@JsonIgnoreProperties(ignoreUnknown = true)
class Users {
  .......
  .......
}
Manjunath H M
  • 818
  • 1
  • 10
  • 25