这会为案例类
创建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
?
答案 0 :(得分:12)
但是,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[B](b => JsString(b.a))
同样,您可以使用Reads.apply创建一个Read。
答案 1 :(得分:-1)
隐式val读取:Reads [A] = (JsPath \“ ax”)。read [B] .map(A.apply)