Skip to content

Instantly share code, notes, and snippets.

@dohzya
Last active December 15, 2015 13:59
Show Gist options
  • Save dohzya/5271324 to your computer and use it in GitHub Desktop.
Save dohzya/5271324 to your computer and use it in GitHub Desktop.
Full example of implicit transformation of JsResult into Try
package foo
import scala.util._
import play.api._
import play.api.data.validation.ValidationError
import play.api.libs.json._
object Foo {
case class JsonErrors(errors: Seq[(JsPath, Seq[ValidationError])]) extends Throwable
implicit def jsresult2try[A](jsresult: JsResult[A]) = jsresult.fold(
errors => Failure(JsonErrors(errors)),
res => Success(res)
)
implicit class ToTry[A](val jsresult: JsResult[A]) extends AnyVal {
def asTry = jsresult2try(jsresult)
}
case class User(name: String, age: Int)
implicit val userFormat = Json.format[User]
val json: Try[JsValue] = Try {
// retrieve JSON from network
Json.obj("name" -> "Toto", "age" -> 42)
}
json.flatMap{ js => Json.fromJson[User](js) }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment