【发布时间】:2015-03-17 17:20:01
【问题描述】:
我正在尝试通过在请求正文中发送 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);
}
}
【问题讨论】:
标签: java json validation playframework-2.0