【发布时间】:2015-03-22 05:00:47
【问题描述】:
假设我有两个案例类:Child、Parent,看起来像:
case class Child()
case class Parent(child: Child)
假设我已经实现了Writes[Child]。我想实现Writes[Parent]。
我可以使用组合符来做到这一点:
implicit val parentWrites: Writes[Parent] = (
(__ \ "child").write[Child]
)(unlift(Parent.unapply))
但是使用以下方法,编译器会抱怨它看到类型 Child 而期待 JsValueWrapper:
implicit val parentWrites = new Writes[Parent] {
def writes(parent: Parent) = Json.obj(
"child" -> parent.child
)
}
希望有人可以帮助我了解如何在不使用组合器的情况下实现 Writes[Parent]。
【问题讨论】:
-
Parent和Child的结构是什么?另外,您所说的“无法正常工作”是什么意思?错误是什么? -
我已经按照您的要求澄清了这个问题。课程一点也不有趣。我只是还没弄清楚如何在不使用组合器的情况下正确地为
Writes[Parent]编写writes函数。 -
尝试用这个包裹
parent.child:Json.toJson(parent.child) -
可能会有所帮助:playframework.com/documentation/2.0/ScalaJson 请参阅:将 Scala 值转换为 Json
-
它适用于我没有空的
Child类。
标签: scala playframework playframework-json