public
Created

JSON parsing

  • Download Gist
Parser.scala
Scala
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
import scala.util.parsing.json.JSON
 
case class Widget(name: String, flavour: String)
case class Contract(vendor: String, colour: String, widgets: List[Widget])
 
object Parser {
 
def parseContract(json: String): Option[Contract] = {
for {
AsMap(contract) <- JSON.parseFull(json)
AsString(vendor) <- contract.get("vendor")
AsString(colour) <- contract.get("colour").orElse(Some("None"))
AsList(widgets) <- contract.get("widgets")
} yield {
Contract(vendor, colour, for {
AsMap(widget) <- widgets
AsString(name) <- widget.get("name")
AsString(flavour) <- widget.get("flavour").orElse(Some("Strawberry"))
} yield Widget(name, flavour))
}
}
}
 
/*
* Some extractors to avoid boilerplate and casting
*/
object AsList {
def unapply(list: List[Any]): Option[List[Any]] = Some(list)
}
 
object AsMap {
def unapply(map: Map[String, Any]) = Some(map)
}
 
object AsString {
def unapply(str: String) = Some(str)
}
 
object Test {
val json = """
{
"vendor" : "Whoever",
"colour" : "blue",
"widgets" :
[
{
"name" : "One",
"flavour" : "Lime"
},
{
"name" : "Two",
"flavour" : "Banana"
},
{
"name" : "Three"
}
]
}"""
 
def main(args: Array[String]) {
println(JSON.parseFull(json))
println(Parser.parseContract(json))
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.