Skip to content

Instantly share code, notes, and snippets.

@parth-patil
Last active February 25, 2016 14:10
Show Gist options
  • Save parth-patil/313f6a669453c2f6925c to your computer and use it in GitHub Desktop.
Save parth-patil/313f6a669453c2f6925c to your computer and use it in GitHub Desktop.
Json4s Examples
/**
* Make sure you include the following in your build.sbt
"org.json4s" %% "json4s-core" % "3.2.10",
"org.json4s" %% "json4s-jackson" % "3.2.10"
*/
import org.json4s._
import org.json4s.jackson.JsonMethods._
import org.json4s.JsonDSL._
case class Candidate(name:Option[String], age:Option[Int], party:Option[String])
object JsonTest extends App{
// Import DefaultFormats which has unmarshallers defined
// for common data structures List, Map etc ...
implicit val formats = DefaultFormats
testJsonCreation()
testJsonParsing()
testJsonCreationWithImplicitConversion()
def testJsonCreation(): Unit = {
val candidates = List(
Candidate(name = Some("Mitt Romney"), age = Some(65), party = None),
Candidate(name = Some("Barack Obama"), age = Some(51), party = Some("Democrat"))
)
val jsonAst =
(
"candidates" -> candidates.map {
c => ("name" -> c.name) ~ ("age" -> c.age) ~ ("party" -> c.party) }
)
println("--------------- testJsonCreation -------------")
println(pretty(render(jsonAst)))
println("----------------------------------------------")
}
// If you have an implicit conversion for your class instance to JValue
// It will be used automatically to create the JSON AST
def testJsonCreationWithImplicitConversion(): Unit = {
implicit def candidate2JValue(c: Candidate): JValue = {
("name" -> c.name) ~ ("age" -> c.age) ~ ("party" -> c.party)
}
val candidates = List(
Candidate(name = Some("Mitt Romney"), age = Some(65), party = None),
Candidate(name = Some("Barack Obama"), age = Some(51), party = Some("Democrat"))
)
val json = ("candidates" -> candidates)
println("--------------- testJsonCreationWithImplicitConversion -------------")
println(pretty(render(json)))
println("--------------------------------------------------------------------")
}
def testJsonParsing(): Unit = {
val jsonString =
"""
|{
| "candidates": [
| {
| "name": "Mitt Romney",
| "age": 65,
| "party": "Republican"
| },
| {
| "name": "Barack Obama",
| "age": 51,
| "party": "Democrat"
| }
| ]
|}
""".stripMargin
val jsonAst: JValue = parse(jsonString)
// Use XSL style querying on JSON AST
val candidates = (jsonAst \ "candidates").extract[List[Candidate]]
println("---------------- testJsonParsing ----------------")
candidates foreach println
println("-------------------------------------------------")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment