Manage JSON error on Play2 controller using scala

This is my first experience with scala. I am trying to make a small REST controller using Play2.

My main goal is to have a POST route with some json data in the body.

This is what I have already done:

def instMeasurement(variable: String) = Action { request =>
    request.body.asJson.map { json =>
        val measurement = MongoDBObject(
            "variable" -> variable,
             "quantity" -> (json \ "quantity").asOpt[Float].getOrElse(BadRequest("Missing parameter [quantity]")),
             "when" -> (json \ "occurTime").asOpt[String].getOrElse(BadRequest("Missing parameter [occurTime]")))

        dao("powermeter").save(measurement)

        Ok(json)
    }.getOrElse(
        BadRequest(Json.toJson("JSON Body missing"))
    )
}

Everything works fine except for the error process. I would like to upgrade to BadRequest.

The Play 2 docs show an example of lubrication:

def sayHello = Action { request =>
  request.body.asJson.map { json =>
    (json \ "name").asOpt[String].map { name =>
      Ok("Hello " + name)
    }.getOrElse {
      BadRequest("Missing parameter [name]")
    }
  }.getOrElse {
    BadRequest("Expecting Json data")
  }
}

It sounds great, except that it doesn't show how to handle multiple values ​​in json.

How can I do the same with two values ​​in json (e.g. name and name)? How can I parse json and the route to BadRequest if json is not complete?

+3
source share
1 answer

, . :

    val fields = List("firstname", "lastname")
    val options = fields.map(name => (json \ name).asOpt[String])
    val errors = options.zip(fields).collect { 
         case (None, f) => f
   }

   if(errors.isEmpty){  Ok(options.flatten.mkString(" "))} 
   else { BadRequest("Missing Fields: " + errors.mkString(" \n "))
0

All Articles