【问题标题】:Play framework 2.5 Json post request binderPlay framework 2.5 Json post request binder
【发布时间】:2016-04-21 12:16:25
【问题描述】:

我有以下课程:

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;
}

还有这样的控制器动作:

@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")));
    }
}

当我使用如下所示的 json 对象从 $.ajax 发布 JSON 时:

    {
      "id":"1",
      "userId":"1",
      "note":"adsfadsfdsaaf",
      "tags":["5","6"]
    }

我无法绑定表单的标签属性,我做错了什么?

我目前正在通过仅使用以下代码解决此问题,但我无法使用表单帮助程序利用 Play 框架验证:

NoteForm note = Json.fromJson(json, NoteForm.class);

【问题讨论】:

  • 很奇怪。 List&lt;String&gt; tags; 也会失败吗?
  • 刚刚试过了,还是不行。
  • 您不会缺少 getter 和 setter 吗?是否设置了 Content-type: application/json 标头?
  • @Sivakumar 我在发布之前确实审查了该问题,如果您查看我发布的代码,我有 cmets 证明我试图做与您链接的帖子相同的事情。 //Form noteForm = NOTE_FORM.bindFromRequest();

标签: java json playframework playframework-2.0 playframework-2.5


【解决方案1】:

我能够使用:

public List&lt;Integer&gt; tags;

并具有这样的表单绑定:

Form<NoteForm> noteForm = formFactory.form(NoteForm.class).bind(request().body().asJson());

在绑定后记录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={})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-14
    • 2017-03-28
    • 1970-01-01
    • 1970-01-01
    • 2019-04-01
    相关资源
    最近更新 更多