mp_loki mp_loki - 22 days ago 5x
JSON Question

Scala Play Json implicit writes type mismatch

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 => {
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

The line:
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:


It gave me a different error, which partially explained why existing Writes object did not suit:

type mismatch;



However, I don't understand the nature of this error and what
is .
I used to do a similar thing in a different example, and it worked just fine.
Any help will be appreciated.


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