Skip to content

Instantly share code, notes, and snippets.

@arschles
Created October 2, 2013 23:03
Show Gist options
  • Save arschles/6801836 to your computer and use it in GitHub Desktop.
Save arschles/6801836 to your computer and use it in GitHub Desktop.
//the class into which we want to decode some JSON
//the JSON looks like this: {"one": 1, "two": 2}
case class MyClass(one: Int, two: String)
val MyClassJSONR: JSONR[MyClass] = new JSONR[MyClass] {
//the method that transforms some JSON into a Result
//Result is either a Failure (instead of throwing an exception) or Success
override def read(json: JValue): Result[MyClass] = {
val fieldOne: Result[Int] = field[Int]("one")(json)
val fieldTwo: Result[Int] = field[Int]("two")(json)
for {
one <- fieldOne
two <- fieldTwo
} yield {
MyClass(one, two)
}
}
val myClassResult: Result[MyClass] = fromJSON[MyClass](someJSON)(MyClassJSONR)
//myClassResult is either:
// - a Failure describing why we couldn't decode the JSON
// - a Success with the MyClass instance in it
//type safety rules!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment