I am trying to add validation to my DTO if a particular field is missing or the field is blank then an error should be thrown that a particular field is missing or is not present I am using object mapper to map the fields eg
StudentDto studentDto = mapper.convertValue(jsonObject, StudentDto.class);
DTO class
@Data
@FieldDefaults(level = AccessLevel.PRIVATE)
public class StudentDto {
@NotNull(message = "FirstName is null")
@NotBlank(message = "FirstName is missing")
String firstName;
@NotNull(message = "LastName is null")
@NotBlank(message = "LastName is missing")
String lastName;
}
I will receive all the values from jsonObject and then I will map those values to DTO. An error should be thrown when a particular field is missing or is blank.But currently I don't receive error the program executes successfully what can I do the achieve this
With Jackson 2.6 you can use required, Although you must define a constructor annotated with @JsonCreator
and use @JsonProperty(required = true)
for each field to force Jackson to throw an exception on your JSON's missing and null fields.
From docs:
Note that as of 2.6, this property is only used for Creator Properties, to ensure existence of property value in JSON: for other properties (ones injected using a setter or mutable field), no validation is performed. Support for those cases may be added in future. State of this property is exposed via introspection, and its value is typically used by Schema generators, such as one for JSON Schema.
@Data
@FieldDefaults(level = AccessLevel.PRIVATE)
public class StudentDto {
String firstName;
String lastName;
@JsonCreator
public StudentDto(@JsonProperty(value = "firstName", required = true) String firstName,//
@JsonProperty(value = "lastName", required = true) String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
}