Since your JSON object is coming from the request, you could actually use Play's Form facility to handle your situation.
In your controller method you would simply call it as below:
final Form<Example> form = Form.form(Example.class).bindFromRequest();
to bind the data from the request. Then you can check to see if there are any errors like this:
if(from.hasErrors()) {
return badRequest(form.errorsAsJson());
}
and retrieve the object from the form if no errors
Example obj = form.get();
Your Example class would also need to changed to use Play's validation Contraints:
import play.data.validation.Constraints;
...
class Example{
@Constraints.Required public String name;
@Constraints.Required public boolean dead;
@Constraints.Required public Integer age;
.
.
50 more values
}
EDIT: I should note here that your JSON object property names and class property variable names have to be the same for the mapping to work automatically.
This way is pretty nice as the errors that it returns are field specific so you can display them to your users and it will return all the error for all the fields in one json object (form.errorsAsJson()
). You also have the added benefit of using the other validation annotations provided by Play (e.g. @Contraints.Email
,@Constraints.MinLenth
etc.)
Note that this worked for me on Play 2.3.x
. I haven't use any recent version of play so YMMV.