JS client of rest api can send both int and string as a value of some field.
{
field1: "123",
field2: "456"
}
{
field1: 123,
field2: 456
}
Here is play action with case class to which json request body should be converted:
case class Dto(field1: Int, field2: Int)
object Dto {
implicit val reads = Json.reads[Dto]
}
def create = Action.async(BodyParsers.parse.json) { implicit request =>
request.body.validate[Dto].map {
dto => someService.doStuff(dto).map(result => Ok(Json.toJson(result)))
}.recoverTotal {
e => jsErrorToBadRequest(e)
}
}
In case if I send json values with int values, it works ok. But in case if field1 or field2 are strings ("123", "456"), it fails, because request.body.validate expects Int.
But problem is that JS client sends values from input fields, and input fields are converted to strings.
What is the best way to handle either ints or strings? (So this action should convert json to dto in both cases)