Created
May 10, 2017 07:55
-
-
Save seance/f0d211086b1cd8f31b6c523e310312f9 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import play.api.libs.json._ | |
import play.api.libs.json.Reads._ | |
import play.api.libs.functional.syntax._ | |
import scala.util.control.Exception._ | |
object Main extends App { | |
case class Person(name: String, height: Double) | |
val goodJson = Json.parse(""" | |
{ | |
"foo": "bar", | |
"baz": "1.4" | |
} | |
""") | |
val badJson = Json.parse(""" | |
{ | |
"foo": "bar", | |
"baz": "Unparseable" | |
} | |
""") | |
def toNum(implicit r: Reads[String]) = Reads[JsNumber]( | |
r.reads(_).flatMap(s => | |
allCatch.either(s.toDouble).fold( | |
_ => JsError("error.expected.jsnumber"), | |
d => JsSuccess(JsNumber(d))))) | |
val readPerson = ( | |
(__ \ 'foo).read[String] ~ | |
(__ \ 'baz).json.update(toNum).andThen( | |
(__ \ 'baz).read[Double] | |
) | |
)(Person) | |
println(goodJson.validate[Person](readPerson)) // JsSuccess(Person(bar,1.4),) | |
println(badJson.validate[Person](readPerson)) // JsError(List((/baz,List(ValidationError(List(error.expected.jsnumber),WrappedArray()))))) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment