简体   繁体   English

[PlayFramework 2.5] [Java]将JSON发布请求绑定到表单中

[英][PlayFramework 2.5][Java] JSON post request binding into form

My controller is for REST service and should receive JSON : 我的控制器用于REST服务,应该接收JSON:

body {
  "text": "string",
  "page": 0
}

I created class according to this: 我根据这个创建了类:

@ApiModel(
        value="FSearch",
        description = "Parameters for user search"

)
public class FSearch {

@ApiModelProperty(
    value = "Text , to lookup for",
    notes = "Can be empty",
    required = false
)
 public String text;

 @ApiModelProperty(
    value = "Page number of search results",
     required = true
 )
 @Constraints.Required
 public int page;

}

My controller bidning looks like this: 我的控制器出价如下所示:

@BodyParser.Of(BodyParser.Json.class)
public Result search(){
 Form<FSearch> searching = formFactory.form(FSearch.class).bindFromRequest();
 if (searching .hasErrors()) {
      return badRequest(searching .errorsAsJson());
 }
  //Another not releated code
  return ok(Json.toJson(result));
}

Now when I test with sending data like this: 现在,当我测试发送这样的数据时:

curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' -d '{ \ "text": "bla", \ "lol": 0 \ }'

So I am sending this JSON: 所以我要发送这个JSON:

body {
  "text": "bla",
  "lol": 0
}

Notice lol instead of page, but form is still binded without any errors... What should I do to ensure that variable names match in json binding? 注意大声笑而不是页面,但是表单仍然被绑定而没有任何错误...我该怎么做以确保变量名称在json绑定中匹配?

This is very poorly documented, but the Required annotation is essentially not much more than a null -check . 这是非常糟糕的文档,但是Required注释本质上只不过是null -check Since an int will never be null , it will therefor always pass. 由于int永远不会为null ,因此它将始终通过。 Either make the field an Integer (which can be null ), or use one of the number based constraints like Min to check if its a valid value other than the default (assuming that there is a number that can be marked as invalid, like a negative one or something). 您可以将字段设为Integer (可以为null ),也可以使用基于数字的约束之一(如Min来检查其默认值以外的有效值(假设有一个数字可以标记为无效值,例如否定一个或多个)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM