Home > Software design >  How to validate PUT requestBody for NotNull constraints only when the object key is passed
How to validate PUT requestBody for NotNull constraints only when the object key is passed

Time:01-23

I am using Spring @RequestBody, and I want to use @NotNull constraints only on the keys which are present in request otherwise, not throw any error.

public class Test {
    private List<String> a;
    private String b;
}

eg 1. No Error

{
  b = "1"
} 

eg 2. Error B cannot be null

{
  b = null
}

eg 3. Error A cannot be null

{
  a = null,
  b = "1"
} 

I can use @NotNull constraints but that makes the keys required. I dont want the keys to be required as there are cases in which I only want to post body with { b : "1" }.

CodePudding user response:

Jackson provides an annotation that can be used on class level (@JsonIgnoreProperties(ignoreUnknown = true).

CodePudding user response:

I think your use-case needs a custom deserializer.

  •  Tags:  
  • Related