java-播放2.3验证Json请求主体
作者:互联网
我正在尝试通过在请求正文中发送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);
}
}
解决方法:
谢谢和平!
由于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);
}
无论如何,我真的不喜欢用表格来做…没有更好的选择了吗?
标签:validation,playframework-2-0,json,java 来源: https://codeday.me/bug/20191120/2045176.html