Ray Wu
Ray Wu

Reputation: 1023

a maintainable way to validate keys/values in a JSON like property map

I am writing a java program to validate keys and values in a property map, which could treat as a JSON object. Right now I am using deeply nested if-else to validate that but it's crazy error-prone. Not sure if this could be easily solved in any design pattern.

Take player property map for example:

'player' = {'name': 'player1', 
            'age': 18, 
            'race': 'human',
            'skills': 'pick pocket',
            'misc': { 'hoppy': 'sleep', 'exp': 238459 }
           };

I want to validate few things

This property map will be extended in the future. What design would make it more extendable?

Upvotes: 0

Views: 1151

Answers (1)

Kumar Sambhav
Kumar Sambhav

Reputation: 7765

Start with the Java class. You can reduce much of your effort by using JSR-303 validation annotaions.

Example :-

class Player{

    @NotNull
    @Size(min=5,max=200)
    private String name;

    @Min(value=10)
    @Max(value=60)
    private int age;

    .
    .
    . // other fields
}

Find available validation annotations here and tutorial here.

Applying the validation on Java bean instead of JSON string/object will be better approach in my opinion.

Converting the bean from and to JSON string is easier using Google's GSON API

Upvotes: 1

Related Questions