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...