根据实例类型写入 JSON
Writing JSON depending on instance type
我在 Play for Scala 中有以下 class 结构:
sealed trait Father
final case class Child1 (name: String, descrip: String) extends Father
final case class Child2 (age: Int, price: Int) extends Father
case class MyClass (someValue: Int, father: Father)
现在,我需要为 MyClass
:
定义隐式 JSON 函数
implicit val myClassWrite : Writes[MyClass] = (
(JsPath \ "some").write[Int] and
(JsPath \ "father").write[Father]
) (unlift(MyClass.unapply))
我得到的是:
No Json serializer found for type Father. Try to
implement an implicit Writes or Format for this type.
问题是无法为 Father
编写 Writes JSON 函数,因为它是没有属性的特征。我只能为 Child1
和 Child2
编写 JSON 函数,但我仍然得到错误。我的意图是让 Play 根据实例类型插入 Child1
或 Child2
的 JSON。 Play 可以做到这一点吗?
implicit val c1 = Json.format[Child1]
implicit val c2 = Json.format[Child2]
implicit val fatherWrites = new Writes[Father] {
override def writes(o: Father) = o match {
case x: Child1 => c1.writes(x)
case x: Child2 => c2.writes(x)
}
}
// 测试
val father : Father = Child1("aa","aaa")
Json.toJson(father).toString() // {"name":"aa","descrip":"aaa"}
我在 Play for Scala 中有以下 class 结构:
sealed trait Father
final case class Child1 (name: String, descrip: String) extends Father
final case class Child2 (age: Int, price: Int) extends Father
case class MyClass (someValue: Int, father: Father)
现在,我需要为 MyClass
:
implicit val myClassWrite : Writes[MyClass] = (
(JsPath \ "some").write[Int] and
(JsPath \ "father").write[Father]
) (unlift(MyClass.unapply))
我得到的是:
No Json serializer found for type Father. Try to implement an implicit Writes or Format for this type.
问题是无法为 Father
编写 Writes JSON 函数,因为它是没有属性的特征。我只能为 Child1
和 Child2
编写 JSON 函数,但我仍然得到错误。我的意图是让 Play 根据实例类型插入 Child1
或 Child2
的 JSON。 Play 可以做到这一点吗?
implicit val c1 = Json.format[Child1]
implicit val c2 = Json.format[Child2]
implicit val fatherWrites = new Writes[Father] {
override def writes(o: Father) = o match {
case x: Child1 => c1.writes(x)
case x: Child2 => c2.writes(x)
}
}
// 测试
val father : Father = Child1("aa","aaa")
Json.toJson(father).toString() // {"name":"aa","descrip":"aaa"}