user2992188
user2992188

Reputation: 293

Validating JSON inside a POJO

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

Upvotes: 7

Views: 1703

Answers (1)

Andrey Chaschev
Andrey Chaschev

Reputation: 16476

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.

Upvotes: 1

Related Questions