Is there a way to validate json attributes based on predefined values in java?

204
February 13, 2018, at 5:04 PM

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.

Answer 1

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/

Rent Charter Buses Company
READ ALSO
how to print this pattern. here dashes are used to depict the spaces between, n is starts from 3 to 5, 7, 9 and so on, [on hold]

how to print this pattern. here dashes are used to depict the spaces between, n is starts from 3 to 5, 7, 9 and so on, [on hold]

Click the link to get the pattern, there is an image attachedhere is the pattern

186
Java ArrayList String Comparator

Java ArrayList String Comparator

I want to check if a String variable is equal to some String variable that is inside an ArrayListWithout using iterator, for, for each

314
Creating a board game

Creating a board game

Basically I'm creating a board game in java and have managed to create cells, using arrays, to look like a 10x10 gridNow I've numbered them they go from left to right top to bottom (as pic) I'm creating a game similar to a snakes and ladders game but having...

217
G1GC very high GC count and CPU, very frequency GCs that kill performance

G1GC very high GC count and CPU, very frequency GCs that kill performance

I've recently switched my Java application from CMS + ParNew to G1GCWhat I observed when I did the switch is the CPU usage went higher and the GC count + pause time went up as well

194