Play Framework JSON Reader and custom JSErrors

2019-04-13 19:08发布

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条回答
兄弟一词,经得起流年.
2楼-- · 2019-04-13 19:42

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.

查看更多
登录 后发表回答