Book Image

Mastering play framework for scala

By : Shiti Saxena
Book Image

Mastering play framework for scala

By: Shiti Saxena

Overview of this book

Table of Contents (21 chapters)
Mastering Play Framework for Scala
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Free Chapter
1
Getting Started with Play
Index

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 also tolerant parsers. By tolerant, we mean that errors in a format are not ignored. This simply means that it ignores the content type header in the request...