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 and parses based on the type specified. For example, let's update the subscribe
method:
def subscribe = Action(parse.tolerantJson) { request => val reqData: JsValue = request.body val emailId = (reqData "email").as[String] val interval = (reqData "interval").as[String] Ok(s"added $emailId to subscriber's list and will send updates every $interval") }
Now, a request with the content type as text and a request where the content type text/JSON, or any other type for that matter, will give the same result. There are tolerant parsers for all the basic parsers supported in Play.
18.224.54.168