Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating JSON inside a POJO

Tags:

java

json

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...
}
like image 919
user2992188 Avatar asked Nov 14 '13 16:11

user2992188


1 Answers

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.

like image 107
Andrey Chaschev Avatar answered Oct 16 '22 16:10

Andrey Chaschev