Adas Adas - 20 days ago 4x
Scala Question

Parsing HTTP request JSON body in scala with play

I am using Scala with Play and looking for a cleaner way to write POST request handler below:

def create = Action.async { request => {
request.body.asJson match {
case Some(x) => x.validate[UserDto] match {
case c: JsSuccess[UserDto] => doActualWork(c.get)
case e: JsError => Future.successful(BadRequest(""))
case None => Future.successful(BadRequest(""))


  1. Many lines required for only parsing JSON object UserDto (which is a common procedure)

  2. Highly nested (poor readability)


Use json body parser. Now body of the request contains json automatically and you can get rid of outer pattern match.

def create = Action.async(parse.json) {
    _.body.validate[UserDto] match {
      case JsSuccess(value, _) => doActualWork(value)
      case _ => Future.successful(BadRequest("bad json body"))

It is advisable to say what went wrong here instead of saying bad json body