【问题标题】:[PlayFramework 2.5][Java] JSON post request binding into form[PlayFramework 2.5][Java] JSON post 请求绑定成表单
【发布时间】:2023-04-10 00:13:01
【问题描述】:

我的控制器用于 REST 服务,应该接收 JSON:

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

我根据这个创建了类:

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

}

我的控制器出价如下所示:

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

现在当我测试发送这样的数据时:

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

所以我要发送这个 JSON:

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

注意大声笑而不是页面,但表单仍然绑定没有任何错误...... 我应该怎么做才能确保 json 绑定中的变量名匹配?

【问题讨论】:

    标签: java json forms rest playframework


    【解决方案1】:

    这是 非常 记录不佳,但 Required 注释是 essentially not much more than a null-check。由于int 永远不会是null,因此它将始终通过。要么将字段设为Integer(可以是null),要么使用基于数字的约束之一,如Min,检查它是否是默认值以外的有效值(假设有一个数字可以标记为无效,例如否定或其他)。

    【讨论】:

      猜你喜欢
      • 2014-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多