Skip to content

Instantly share code, notes, and snippets.

@jruusu
Last active February 11, 2016 12:41
Show Gist options
  • Save jruusu/d2503976f90b48846437 to your computer and use it in GitHub Desktop.
Save jruusu/d2503976f90b48846437 to your computer and use it in GitHub Desktop.
Play 2.4 Json Formats with Recursive Types
import play.api.libs.functional.syntax._
import play.api.libs.json._
case class Foo(id: String, bar: Option[Bar])
object Foo {
implicit val format = Json.format[Foo]
}
case class Bar(id: String, foos: Option[Seq[Foo]])
object Bar {
implicit val format: Format[Bar] = (
(__ \ 'id).format[String] and
(__ \ 'foos).lazyFormatNullable(implicitly[Format[Seq[Foo]]])
)(Bar.apply, unlift(Bar.unapply))
}
// foo1 contains bar1 which contains foo2
val jsonStr = """{ "id": "foo1", "bar": { "id": "bar1", "foos": [ { "id": "foo2" } ] } }"""
val json = Json.parse(jsonStr)
val foo = json.as[Foo]
// Did it work?
foo.bar.flatMap(_.foos).flatMap(_.headOption).map(_.id).contains("foo2")
// Complete round trip
Json.toJson(foo)
@jruusu
Copy link
Author

jruusu commented Feb 11, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment