Skip to content

Instantly share code, notes, and snippets.

@lasiltan
Created February 11, 2016 12:35
Show Gist options
  • Save lasiltan/b8bd06c292b42245f57e to your computer and use it in GitHub Desktop.
Save lasiltan/b8bd06c292b42245f57e to your computer and use it in GitHub Desktop.
json4s extract and serialize
import org.json4s.jackson.JsonMethods._
import org.json4s._
import org.json4s.jackson.Serialization
import org.json4s.jackson.Serialization.write
implicit val formats = Serialization.formats(NoTypeHints)
case class Foo(id: String, bar: Option[Bar])
case class Bar(id: String, foos: Option[Seq[Foo]])
// foo1 contains bar1 which contains foo2
val jsonStr = """{ "id": "foo1", "bar": { "id": "bar1", "foos": [ { "id": "foo2" } ] } }"""
val json = parse(jsonStr)
val foo = json.extract[Foo]
// Did it work?
foo.bar.flatMap(_.foos).flatMap(_.headOption).map(_.id).contains("foo2")
// Complete round trip
write(foo)
@lasiltan
Copy link
Author

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