Java complex validation in Dropwizard?

Posted by miku on Stack Overflow See other posts from Stack Overflow or by miku
Published on 2012-12-14T16:52:41Z Indexed on 2012/12/14 17:03 UTC
Read the original article Hit count: 550

Filed under:
|
|
|
|

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.

© Stack Overflow or respective owner

Related posts about java

Related posts about JSON