这为案例类创建了Writes
import play.api.libs.json._
import play.api.libs.functional.syntax._
case class A(a: String, b: String, c: String)
(JsPath.write[String] and
JsPath.write[String] and
JsPath.write[String])(unlift(A.unapply))
这可以扩展为适用于2,3,4,5,6等参数......但不能用于1。
case class B(a: String)
(JsPath.write[String])(unlift(B.unapply))
编译错误:
error: overloaded method value write with alternatives:
(t: String)(implicit w: play.api.libs.json.Writes[String])play.api.libs.json.OWrites[play.api.libs.json.JsValue] <and>
(implicit w: play.api.libs.json.Writes[String])play.api.libs.json.OWrites[String]
cannot be applied to (B => String)
(JsPath.write[String])(unlift(B.unapply))
^
类似的问题发生在Reads
。
我怎样才能获得Reads
和Writes
的单参数案例条款?
像特拉维斯说:
但是,contramap仅适用于生成JsObject的Writes。您的写入将在运行时失败:
val w = JsPath.write[String].contramap[B](_.a)
scala> w.writes(B("Hello"))
java.lang.RuntimeException: when empty JsPath, expecting JsObject
您可以使用Writes.apply
“从头开始”创建一个Writes:
Writes[B](b => JsString(b.a))
同样,您可以使用Reads.apply创建Reads。
隐式val读取:读取[A] =(JsPath \“ax”)。读取[B] .map(A.apply)