What is the best/preferred way to validate JSON using annotations inside a POJO? I would like to be able to distinguish between optional and required fields of a POJO. I would like to be able to provide default values for required fields of a POJO.
Example:
@JsonTypeInfo(use=Id.NAME, include = As.WRAPPER_OBJECT)
@JsonTypeName("Foo")
public class MyClass{
@JsonProperty
private String someOptionalField;
@JsonProperty
private String someRequiredField;
@JsonProperty
private String someRequiredFieldThatIsNotNull;
@JsonProperty
private int someRequiredFieldThatIsGreaterThanZero;
// etc...
}
A possible approach is to deserialize JSON into an object and validate an object with validation API @MattBall linked. The advantage is that this logic is being decoupled from storage logic and you are free to change your storage logic with no need to reimplement validation.
If you want to validate JSON, you might want to have a look at JSON schema.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With