How to make a controller’s action method containing two different bodyparser? For example,
@BodyParser.Of(BodyParser.Json.class)
@BodyParser.Of(BodyParser.FormUrlEncoded.class)
public static Result register() {
RequestBody body = request().body();
JsonNode node = body.asJson();
Map<String, String[]> map = body.asFormUrlEncoded();
if(node != null) {
return ok("Got: " + node);
} else if (map != null) {
return ok("Got: " + map);
} else {
return badRequest("Expecting application/json request body");
}
}
I don’t think it adheres to conventions to allow a single method to parse two different encodings. You basically want two controller functions in one. I think it’s in best taste to have seperate methods handling the different encoding like so
You can then differentiate between these controller methods in your routes file
(this isn’t pretty RESTfulness, but you get the idea)
Or by determining this is in a controller function. I find this quite ugly but I guess it’s the answer you’re looking for. The trick is to omit the
@BodyParserannotation:As far as I know, there’s no prettier way to do this. There probably shouldn’t be, because you want to map two different methods onto a single one.