私はこのようなケースクラスを持っています:
case class Product(ean: Long, name: String, description: String, purchasePrice: Option[BigDecimal] = None, sellingPrice: Option[BigDecimal] = None)
そして、私はこのような非暗黙の書き込みを持っています:
val adminProductWrites = (
(JsPath \ "ean").write[Long] and
(JsPath \ "name").write[String] and
(JsPath \ "description").write[String] and
(JsPath \ "purchase_price").writeNullable[BigDecimal] and
(JsPath \ "selling_price").writeNullable[BigDecimal]
)(unlift(Product.unapply))
そして、Option[Product] のインスタンスがあります。
val prod = Some(Product(5018206244611L, "Zebra Paperclips", "Zebra Length 28mm Assorted 150 Pack"))
シリアル化しようとすると...:
val jsonStr = Json.toJson(prod) (adminProductWrites)
次のようなエラーが発生しました。
<console>:21: error: type mismatch;
found : play.api.libs.json.OWrites[Product]
required: play.api.libs.json.Writes[Some[Product]]
val jsonStr = Json.toJson(prod) (adminProductWrites)
だから、最初に(比較のために)私はこれを試しました:
val jsonStr = Json.toJson(prod.get) (adminProductWrites)
できます:
jsonStr: play.api.libs.json.JsValue = {"ean":5018206244611,"name":"Zebra Paperclips","description":"Zebra Length 28mm Assorted 150 Pack"}
しかし、私はそれをしたくありません(.getを呼び出します)。Writes が暗黙的として宣言されている場合と同じように作業する必要があります。
implicit object ProductWrites extends Writes[Product] {
def writes(p: Product) = Json.obj(
"ean" -> Json.toJson(p.ean),
"name" -> Json.toJson(p.name),
"description" -> Json.toJson(p.description)
)
}
(その暗黙の書き込みで、この行は機能します):
scala> val jsonStr = Json.toJson(prod)
jsonStr: play.api.libs.json.JsValue = {"ean":5018206244611,"name":"Zebra Paperclips","description":"Zebra Length 28mm Assorted 150 Pack"}
私は何が欠けていますか?
追記:
私の暗黙の書き込みは不完全です。意図的に最後の 2 つのフィールド (purchasePrice と SellingPrice) を削除しました。理由: このコードはコンパイルされません:
implicit object ProductWrites extends Writes[Product] {
def writes(p: Product) = Json.obj(
"ean" -> Json.toJson(p.ean),
"name" -> Json.toJson(p.name),
"description" -> Json.toJson(p.description),
"purchase_price" -> p.purchasePrice.getOrElse(None),
"selling_price" -> p.sellingPrice.getOrElse(None)
)
}
私はこのエラーを出します:
<console>:24: error: No Json serializer found for type Serializable. Try to implement an implicit Writes or Format for this type.
"purchase_price" -> Json.toJson(p.purchasePrice.getOrElse(None)),
前もってありがとう、ラカ