Search code examples
jsonjacksonmappingdropwizardpojo

Jackson Validation when mapping JSON to POJO


Firstly I must confess that I am completely new to Web Services and the DropWizard framework.

I am currently performing a POST request and trying to parse the JSON body into a POJO.

This works great when the JSON is in the required format. However, when a key in the JSON, is missing, my POJO resorts to a default value.

My question is, is there anyway of either checking the JSON for all values or having Jackson throw some sort of exception if a JSON key is missing?

public class PlacedBetDecimal extends PlacedBet {

    private double odds;

    // Empty constructor to please Jackson
    public PlacedBetDecimal() {

    }

    public PlacedBetDecimal(@JsonProperty("bet_id") long bet_id,
                            @JsonProperty("stake") int stake,
                            @JsonProperty("odds") double odds) {

        super.bet_id = bet_id;
        super.stake = stake;
        this.odds = odds;
    }

    public double getOdds() {
        return odds;
    }

    @Override
    public String toString() {
        return "PlacedBetFractional{" +
                "bet_id="+super.bet_id+
                "stake="+super.stake+
                "odds=" + odds +
                '}';
    }
}

The JSON which would be in the body is as follows:

{
    "bet_id": 1,
    "odds": 11.0,
    "stake": 10
}

If for some reason, someone supplied a body with:

{
    "odds": 11.0,
    "stake": 10
}

Then i would like to be able to catch this instead of Jackson auto filling the bet_id to 0.

Any and all help will be greatly appreciated.


Solution

  • Instead of using primitives, use their corresponding type wrappers, e.g. Double instead of double, and mark them with bean validation constraints like @NotNull.

    My question is, is there anyway of either checking the JSON for all values or having Jackson through some sort of exception if a JSON key is missing?

    In my opinion, add Bean Validation constraints to your POJOs and then perform validations on incoming representations. If there was at least one constraint violation, Dropwizard will return a 422 Unprocessable Entity response.

    Suppose you have a Person like:

    public class Person {
    
        @NotEmpty // ensure that name isn't null or blank
        private String name;
    
        @NotNull @Min(18) // at least 18 years old!
        private Integer age;
    
        // getters and setters
    }
    

    Then, in our resource class, we can add the @Valid or the @Validated annotation to the Person:

    @PUT
    public Person replace(@Valid Person person) {
        // do stuff
    }
    

    If the name or age fields were missing, Dropwizard will return a 422 Unprocessable Entity response detailing the validation errors.