Created
September 4, 2011 11:35
-
-
Save alxbok/1192722 to your computer and use it in GitHub Desktop.
JSON parsing
This file contains 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
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