Last active
October 18, 2016 01:17
-
-
Save bigjason/6098549 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.functional.syntax._ | |
import play.api.data.validation.ValidationError | |
implicit class JsPathPimps(path: JsPath) extends JsPath { | |
def readOrError[T](error: => String)(implicit r: Reads[T]): Reads[T] = new Reads[T] { | |
def reads(json: JsValue): JsResult[T] = path.readNullable(r).reads(json) match { | |
case JsSuccess(Some(value), _) => JsSuccess(value, path) | |
case JsSuccess(None, _) => JsError((path, ValidationError(error))) | |
case err@JsError(_) => err | |
} | |
} | |
def formatOrError[T](error: => String)(implicit r: Format[T]): OFormat[T] = | |
OFormat(readOrError(error), Writes.at(path)(r)) | |
} | |
implicit val reader = ( | |
(__ \ 'name).readOrError[String]("Username undefined") and | |
(__ \ 'email).readOrError[String]("Email undefined") | |
).tupled | |
val jsonTest = Json.obj("name" -> "julien") | |
jsonTest.validate(reader) | |
> JsError(List((,List(ValidationError(Email undefined,WrappedArray()))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment