Created
October 2, 2013 23:03
-
-
Save arschles/6801836 to your computer and use it in GitHub Desktop.
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
//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