Martin Dluhy
Martin Dluhy

Reputation: 143

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

My controller is for REST service and should receive 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:

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?

Upvotes: 0

Views: 170

Answers (1)

gpgekko
gpgekko

Reputation: 3596

This is very poorly documented, but the Required annotation is essentially not much more than a null-check. Since an int will never be null, it will therefor always pass. 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).

Upvotes: 1

Related Questions