问题
I'm trying to read a JSON that could have the following parameters coming from the client
{
"email" : "foobar@gmail.com",
"password" : "XXXX",
"facebookToken": "XXXXXXXXXXX"
}
The facebookToken could be Null or Not present, in which case the Email/Password should be filled, and vice versa.
I'm having trouble constructing this Reader, here's what I have so far:
val loginEmail = (
( __ \ "email").read[String] and
( __ \ "password").read[String]
)((email: String, password: String) => new User(email, password))
val loginFacebook = (
( __ \ "facebookToken").read[String]
)((facebookToken : String) => new User(facebookToken))
val loginReader(RequestBodyJson) = (
(RequestBodyJson).read[User](loginEmail) or
(RequestBodyJson).read[User](loginFacebook)
)
Can anyone show me how to do this correctly?
I would also like it to return JSError with customized messages. For instance, if the FacebookToken is not present, and there was something wrong with the Email ("Email was Invalid") instead of "/facebookToken path not found" generic error.
回答1:
You can use this tricks:
import play.api.libs.json._
import play.api.libs.functional.syntax._
import play.api.data.validation.ValidationError
....
(__ \ "facebookToken").read[String].orElse(Reads(_ => JsError(ValidationError("custom-error"))))
You can return a custom JsError if the main reader fail.
来源:https://stackoverflow.com/questions/17818924/play-framework-json-reader-and-custom-jserrors