I'm trying to use the validation annotations within a pojo object by sending json in the body of the request and converting the json to the pojo object. What I would like to do is have the service consuming this json to return a bad request if the object is not valid. Does anyone know how to go about doing this? I've seen plenty of tutorials that show how to do form validation using the annotations, but what about just a simple json request?
POJO Object:
import play.data.validation.Constraints.*;
public class TestObject {
@Required
@Min(0)
public Integer testInt;
public Integer getTestInt() {
return testInt;
}
public void setTestInt(Integer testInt) {
this.testInt = testInt;
}
}
I could probably look at every element by parsing the json and validate it that way, but that seems ridiculous...
import models.Domain;
import play.libs.Json;
import play.mvc.BodyParser;
import play.mvc.Controller;
import play.mvc.Result;
import com.fasterxml.jackson.databind.JsonNode;
public class TestController extends Controller {
@BodyParser.Of(value = BodyParser.Json.class, maxLength = 10 * 1024)
public static Result create() {
JsonNode json = request().body().asJson();
TestObject testObject = Json.fromJson(json, TestObject.class);
//would like to validate the object here, based on annotations
//in the bean object...
//only if the object is valid, return ok...
return ok(json);
}
}
Aucun commentaire:
Enregistrer un commentaire