Hi,
Play's JSON library provides typeclass-based Reads/Writes API (which is nice) but imho it's pretty useless.
There are basically two functions for parsing "as" and "asOpt"
someJsValue.as[String] ==> String or exception
someJsValue.asOpt[String] ==> Option[String] cool
but...
Consider this simple example
case class Foo(a: String, b: Int)
implicit def FooReads: Reads[Foo] = new Reads[Foo]{
def reads(json: JsValue): Foo = {
for {
a <- (json \ "a").asOpt[String] // secure parsing
b <- (json \ "b").asOpt[Int] // also secure
} yield Foo(a,b) /
}
}
To above code will not compile, since return type of "reads" is Foo, not Option[Foo]. It has to be written like
implicit def FooReads: Reads[Foo] = new Reads[Foo]{
def reads(json: JsValue): Foo = Foo(
(json \ "a").as[String], // Hello exceptions!
(json \ "b").as[Int] // Exception again
)
}
"asOpt" solves nothing.
Why reads is not JsValue => Option[T] ? (Or even some Validation)