[英]Play framework 2.5 Json post request binder
I have a class with the following :我有一堂课,内容如下:
public class NoteForm {
public Integer id;
@Constraints.Required
public Integer userId;
@Constraints.Required
public String note;
// cant get any of the following to work
public Int[] tags;
public String[] tags;
public List<int> tags;
}
And a controller action like this:和这样的控制器动作:
@BodyParser.Of(BodyParser.Json.class)
public Result updateNote(){
Form<NoteForm> noteForm = NOTE_FORM.bind(request().body().asJson());
//also have tried the following
//Form<NoteForm> noteForm = NOTE_FORM.bindFromRequest();
if(noteForm.hasErrors()){
return badRequest(noteForm.errorsAsJson());
}else{
noteService.saveNote(noteForm.get());
return jsonResult(ok(Json.toJson("Save Succeeded")));
}
}
When I post JSON from $.ajax using a json object that looks like the following:当我使用如下所示的 json 对象从 $.ajax 发布 JSON 时:
{
"id":"1",
"userId":"1",
"note":"adsfadsfdsaaf",
"tags":["5","6"]
}
I can't get the form's tag property to bind, what am I doing wrong?我无法绑定表单的标签属性,我做错了什么?
I am currently working around this issue by just using the following code, but I am not able to utilize the Play framework validation using the form helper:我目前仅通过使用以下代码来解决此问题,但我无法使用表单助手来利用 Play 框架验证:
NoteForm note = Json.fromJson(json, NoteForm.class);
I was able to make this work using:我能够使用以下方法完成这项工作:
public List<Integer> tags;
and having the form binding like this:并具有这样的表单绑定:
Form<NoteForm> noteForm = formFactory.form(NoteForm.class).bind(request().body().asJson());
Logging the noteForm
after binding gives me this (using your input):绑定后记录
noteForm
给了我这个(使用您的输入):
Form(of=class models.NoteForm, data={note=adsfadsfdsaaf, id=1, tags[1]=6, userId
=1, tags[0]=5}, value=Optional[models.NoteForm@5cd20029], errors={})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.