jbrown jbrown - 9 days ago 5
JSON Question

Play framework: JSON Reads for a single-attribute case class

I'm trying to create a JSON Reads implicit for a case class that contains a single attribute, but I'm getting an error "Reads[Nothing] doesn't conform to expected type". Here's teh codes:

import play.api.libs.functional.syntax._
import play.api.libs.json.Reads._
import play.api.libs.json.{JsPath, Json, Reads}

case class Feedback(message: String)
object Feedback {
implicit val reads: Reads[Feedback] = (
(JsPath \ "message").read[String](maxLength[String](2000))
)(Feedback.apply _)
}


Why isn't this working? If I add extra attributes to the case class and multiple
.read
calls joined with
and
it works...

Answer

Json combinators doesn't work for single field case class.

You can do the following:

import play.api.libs.json.Reads._
import play.api.libs.json.{__, Reads}

case class Feedback(message: String)
object Feedback {
  implicit val reads: Reads[Feedback] = (__ \ "message")
    .read[String](maxLength[String](2000)).map {message => Feedback(message)}
}

It's because of a limitation in the current Macro implementation. You can read more about it here: Pacal is the writer of this API

Comments