【发布时间】:2014-02-06 19:04:17
【问题描述】:
Play for Scala 展示了如何将 JSON 转换为 Scala 对象。
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))
然后在 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"}
最后一行:(unlift(Product.unapply)) 的 Writes[Product] 是怎么回事?
【问题讨论】:
-
请注意,您将获得与
implicit val productWrites: Writes[Product] = Json.writes[Product]相同的Writes。
标签: json scala playframework