Skip to content

Instantly share code, notes, and snippets.

@jrudolph
Created November 15, 2012 09:31
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jrudolph/4077644 to your computer and use it in GitHub Desktop.
Save jrudolph/4077644 to your computer and use it in GitHub Desktop.
json-lenses example
/.idea/
/project/boot/
/project/plugins/project
target/
lib_managed/
src_managed/
test-output/
*.iml
sbt.version=0.12.1
libraryDependencies ++= Seq(
"io.spray" %% "spray-json" % "1.2.2",
"net.virtual-void" %% "json-lenses" % "0.5.1"
)
import spray.json.{DefaultJsonProtocol, JsonParser}
import spray.json.lenses.JsonLenses._
case class Bird(name: String, color: String)
case class Birds(german: String, birds: List[Bird])
case class Ecosystem(ecoSystem: String, birds: Birds)
object BirdJsonProtocol extends DefaultJsonProtocol {
implicit val BirdFormat = jsonFormat(Bird, "name", "color")
implicit val BirdsFormat = jsonFormat(Birds, "german", "birds")
implicit val EcosystemFormat = jsonFormat(Ecosystem, "ecoSystem", "birds")
}
object ExtraPartOfJson extends App {
val jsonString =
"""{
| "ecoSystem": "garden",
| "birds": {
| "german": "Voegel",
| "birds": [{
| "name": "Amsel",
| "color": "black"
| }, {
| "name": "Bussard",
| "color": "brown"
| }]
| }
|}""".stripMargin
val json = JsonParser(jsonString)
println(json.prettyPrint)
import BirdJsonProtocol._
// in spray-routing use:
// result.entity.as[Ecosystem]
val ecosystem = json.as[Ecosystem]
println(ecosystem)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment