Skip to content

@alxbok /Parser.scala
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
JSON parsing
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))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.