Play for Scala shows how to convert JSON to a Scala object.
case class Product(ean: Long, name: String, description: String)
import play.api.libs.json._
import play.api.libs.functional.syntax._
implicit val productWrites: Writes[Product] = (
(JsPath \ "ean").write[Long] and
(JsPath \ "name").write[String] and
(JsPath \ "description").write[String]
)(unlift(Product.unapply))
And then using in REPL:
scala> val p = Product(100, "tilley hat", "Nice hat")
p: Product = Product(100,tilley hat,Nice hat)
scala> Json.toJson(p)
res1: play.api.libs.json.JsValue = {"ean":100,"name":"tilley hat",
"description":"Nice hat"}
What's going on with the last line: (unlift(Product.unapply))
of the Writes[Product]
?
Product.unapply _
is a functionProduct => Option[(Long, String, String)]
.Result type of this expression:
is
FunctionalBuilder[OWrites]#CanBuild3[Long,String,String]
. It acceptsT => (Long, String, String)
as parameter of methodapply
.So you have to convert
Product => Option[(Long, String, String)]
toProduct => (Long, String, String)
.Method
unlift
acceptsT => Option[R]
and returnsT => R
. Unlifted function throwsMatchError
instead ofNone
. It produces something like this:Default
unapply
method for case class should never returnNone
, so for case classunlift
is safe.