Is there a way to validate json attributes based on predefined values in java?
for ex:
{
"operation": "ONE"
}
Only allowed values for operation is ONE, TWO, THREE. So in JSON layer, we want to validate this operation attribute, if request has other than any of the above values, we want to reject it. Is there any JSON annotation to achieve this?
Library used: Fasterxml Jackson
Thanks in Advance.
Well there could be two possible ways : Firstly you can use @JsonProperty but for that you need to add @JsonCreator or custom constructor.
Or else you can simply use Jackson schema validation. Create a schema.json and validate each incoming input against the schema for example :
{
"operation": {
"type":"string",
"required":true,
"enum":["ONE","TWO","THREE"]
}
}
It's better than handling the Exceptions raised i.e. JsonMappingException and UnrecognizedPropertyException by Jackson.
You can look for more about Schema Validation at : http://wilddiary.com/validate-json-against-schema-in-java/