Created
June 16, 2014 01:51
-
-
Save krishnabhargav/7cd67a7ed94d100fb325 to your computer and use it in GitHub Desktop.
JSON deserialization in Scala
This file contains hidden or 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
//CASE CLASSES | |
case class Location(lat: Double, lng: Double) | |
case class Geometry(location: Location) | |
case class RunningStatus(open_now: Boolean) | |
case class Results(geometry: Geometry, icon: Option[String], id: Option[String], name: Option[String], | |
opening_hours: Option[RunningStatus], price_level: Option[Double], rating: Option[Double], | |
reference: Option[String], types: Option[List[String]], vicinity: Option[String]) | |
case class RootJsonObject(results: List[Results]) | |
//JSON imports | |
import org.json4s.jackson.Serialization | |
import org.json4s.jackson.Serialization.{ read } | |
import org.json4s.NoTypeHints | |
private def handleJsonOutput(body: String): Unit = { | |
//required to set implicit here for JSON serialization to work properly | |
implicit val formats = Serialization.formats(NoTypeHints) | |
//read the output as a RootJsonObject instance | |
//the read call does the trick of mapping JSon to the case classes | |
val output = read[RootJsonObject](body) | |
println(s"Total Results: ${output.results.size}") | |
for (each <- output.results) | |
println(s"${each.name.get} at ${each.vicinity.get}") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment