以下内容给了我一个堆栈溢出错误,我不知道为什么会发生。我也尝试使递归类型的隐式格式化程序变得懒惰,但出现相同的错误。有什么想法吗?
import play.api.libs.json._
import play.api.libs.functional.syntax._
sealed trait Foo
object Foo {
implicit val fooReads: Reads[Foo] = Reads[Foo] { json =>
(json \ "discriminator").validate[String].flatMap {
case "Bar" => json.validate[Bar]
case "Baz" => json.validate[Baz]
}
}
implicit val fooWrites: Writes[Foo] = Writes[Foo] {
case bar: Bar => Json.toJson[Bar](bar)
case baz: Baz => Json.toJson[Baz](baz)
}
}
case class Bar(b: String) extends Foo
object Bar {
implicit val barFormat: OFormat[Bar] = Json.format[Bar]
}
case class Baz(c: String, as: Seq[Foo]) extends Foo
object Baz {
implicit val bazFormat: OFormat[Baz] = (
(__ \ "c").format[String] and
(__ \ "as").lazyFormat(implicitly[Format[Seq[Foo]]])
)(Baz.apply, unlift(Baz.unapply))
}
val baz = Baz("aa", Seq(Baz("bb", Seq(Bar("cc")))))
Json.toJson(baz)
答案 0 :(得分:1)
更改代码的这一部分以显式调用正确的格式化程序:
implicit val fooWrites: Writes[Foo] = Writes[Foo] {
case bar: Bar => Json.toJson[Bar](bar)(Bar.barFormat)
case baz: Baz => Json.toJson[Baz](baz)(Baz.bazFormat)
}
由于它们都是Foo
,因此在它们被识别出来并再次调用您的fooWrites
之前,栈就溢出了。您也可以查看play-json-derived-codecs,尽管我从未使用过它。