Advertisement
Guest User

Untitled

a guest
Feb 11th, 2016
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.72 KB | None | 0 0
  1. import play.api.libs.functional.syntax._
  2. import play.api.libs.json._
  3.  
  4. case class Foo(id: String, bar: Option[Bar])
  5. object Foo {
  6. implicit val format = Json.format[Foo]
  7. }
  8.  
  9. case class Bar(id: String, foos: Option[Seq[Foo]])
  10. object Bar {
  11. implicit val format: Format[Bar] = (
  12. (__ \ 'id).format[String] and
  13. (__ \ 'foos).lazyFormatNullable(implicitly[Format[Seq[Foo]]])
  14. )(Bar.apply, unlift(Bar.unapply))
  15. }
  16.  
  17. // foo1 contains bar1 which contains foo2
  18. val jsonStr = """{ "id": "foo1", "bar": { "id": "bar1", "foos": [ { "id": "foo2" } ] } }"""
  19. val json = Json.parse(jsonStr)
  20. val foo = json.as[Foo]
  21.  
  22. // Did it work?
  23. foo.bar.flatMap(_.foos).flatMap(_.headOption).map(_.id).contains("foo2")
  24.  
  25. // Complete round trip
  26. Json.toJson(foo)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement