Extending a parser

Let's extend the JSON parser so that we get a subscription model. We will assume that the Subscription model is defined as follows:

case class Subscription(emailId: String, interval: String) 

Now, let's write a parser that transforms the request body into a subscription object. The following code should be written in a controller:

val parseAsSubscription = parse.using {
    request => 
      parse.json.map {
        body => 
          val emailId:String = (body \ "emailId").as[String] 
          val fromDate:Long = (body \ "fromDate").as[Long] 
          Subscription(emailId, fromDate)
      }
  }

  implicit val subWrites = Json.writes[Subscription]
  def getSub = Action(parseAsSubscription) {
    request => 
      val subscription: Subscription = request.body
      Ok(Json.toJson(subscription))
   } 

There are ...

Get Mastering Play Framework for Scala now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.