Java complex validation in Dropwizard?
- by miku
I'd like to accept JSON on an REST endpoint and convert it to the correct type for immediate validation.
The endpoint looks like this:
@POST
public Response createCar(@Valid Car car) { 
    // persist to DB
    // ... 
}
But there are many subclasses of Car, e.g. Van, SelfDrivingCar, RaceCar, etc. How could I accept the different JSON representations on the endpoint, while keeping the validation code
in the Resource as concise as something like @Valid Car car?
Again: I send in JSON like (here, it's the representation of a subclass of Car, namely SelfDrivingCar):
{ 
    "id" : "t1",                      // every Car has an Id
    "kind" : "selfdriving",           // every Car has a type-hint
    "max_speed" : "200 mph",          // some attribute
    "ai_provider" : "fastcarsai ltd." // this is SelfDrivingCar-specific
}
and I'd like the validation machinery look into the kind attribute, create an instance of the appropriate subclass, here e.g. SelfDrivingCar and perform validation.
I know I could create different endpoints for all kind of cars, but thats does not seem DRY. And I know that I could use a real Validator instead of the annotation and do it by hand, so I'm just asking if there's some elegant shortcut for this problem.