Last active
February 11, 2016 12:41
-
-
Save jruusu/d2503976f90b48846437 to your computer and use it in GitHub Desktop.
Play 2.4 Json Formats with Recursive Types
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Same in json4s: https://gist.github.com/lasiltan/b8bd06c292b42245f57e