我试图通过在请求正文中发送 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);
}
反正我不太喜欢用form来做...没有更好的选择吗?
关于java - Play 2.3 验证 Json 请求体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29105632/