我正在尝试通过在请求正文中发送json并将json转换为pojo对象来在pojo对象中使用验证注释。我想要做的是让服务使用这个json,如果对象无效,则返回错误的请求。有谁知道怎么做这个?我已经看过很多教程,展示了如何使用注释进行表单验证,但只是一个简单的json请求呢?
POJO对象:
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;
}
}
我可以通过解析json来查看每个元素并以这种方式验证它,但这看起来很荒谬......
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);
}
}
答案 0 :(得分:2)
谢谢和平!
由于Play 2.5 Form.form(...)
已被弃用。
以下是您现在应该如何做的事情:
private FormFactory formFactory;
@Inject
YourContructor(FormFactory formFactory){
this.formFactory
}
@BodyParser.Of(value = BodyParser.Json.class, maxLength = 10 * 1024)
public static Result create() {
JsonNode json = request().body().asJson();
Form<TestObject > TestObjectValidationForm = formFactory.form(TestObject .class)
.bind(json);
if(TestObjectValidationForm .hasErrors())
return badRequest("Invalid");
TestObject testObject = Json.fromJson(json, TestObject.class);
//only if the object is valid, return ok...
return ok(json);
}
无论如何,我真的不想用表格去做...没有更好的选择吗?
答案 1 :(得分:1)
这就是我要做的事情
@BodyParser.Of(value = BodyParser.Json.class, maxLength = 10 * 1024)
public static Result create() {
JsonNode json = request().body().asJson();
//this is not neccessary for validation except maybe to be sure the json can be
//mapped back to pojo before validating then you'll have to wrap
//this statement in a try catch so you can recover from any errors during mapping
//TestObject testObject = Json.fromJson(json, TestObject.class);
Form<TestObject> testObjectForm = Form.form(TestObject.class);
Form<TestObject> testObjForm = testObjectForm.bind(json);
if(testObjForm.hasErrors){
doStuff()
}else{
return ok(json);
}
}