Last active
December 15, 2015 13:59
-
-
Save dohzya/5271324 to your computer and use it in GitHub Desktop.
Full example of implicit transformation of JsResult into Try
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
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