Play Framework JSON Reader and custom JSErrors

假装没事ソ 提交于 2019-12-21 22:36:04

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!