Reputation: 1048
I am new to Scala and Play, and I ask for help with this simple example. I tried to search for solution by myself, but I did not succeed. I am trying to do the example from from Mastering Play Framework for Scala book, the one about extending Json parser (Pages 29-30).
The environment I use is:
Scala: 2.11.7 Play: 2.5.8 Activator: 1.3.10
The code is:
case class Subscription(emailId: String, interval: Long)
In controller:
import play.api.libs.json.Json
import play.api.libs.json.JsValue
import play.api.libs.json.Writes
.....
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:Writes[Subscription] = Json.writes[Subscription]
def getSub = Action(parseAsSubscription) {
request =>
val subscription: Subscription = request.body
Ok(Json.toJson(Subscription))
}
The line: Ok(Json.toJson(Subscription))
gives an error
No Json serializer found for type models.Subscription.type. Try to implement an implicit Writes or Format for this type.
This is odd, because Writes object is defined one row above. Thus, I tried to pass it to toJson method explicitly:
Ok(Json.toJson(Subscription)(subWrites))
It gave me a different error, which partially explained why existing Writes object did not suit:
type mismatch;
found: play.api.libs.json.Writes[models.Subscription]
required: play.api.libs.json.Writes[models.Subscription.type]
However, I don't understand the nature of this error and what models.Subscription.type
is .
I used to do a similar thing in a different example, and it worked just fine.
Any help will be appreciated.
Upvotes: 0
Views: 787
Reputation: 1114
You're trying to serialize the type Subscription
, rather than the request body, which you stored as the value subscription
. Try replacing the last line with Ok(Json.toJson(subscription))
.
Upvotes: 2