Adas Adas - 1 year ago 111
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)

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download