播放Framework JSON Reader和自定义JSError [英] Play Framework JSON Reader and custom JSErrors

查看:70
本文介绍了播放Framework JSON Reader和自定义JSError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试读取一个可能具有来自客户端的以下参数的JSON

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"
}

facebookToken 可以为Null或不存在,在这种情况下,应该填写 Email/Password ,反之亦然.

The facebookToken could be Null or Not present, in which case the Email/Password should be filled, and vice versa.

我在构造此Reader时遇到了麻烦,这是我到目前为止所拥有的:

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?

我还希望它返回带有自定义消息的JSError.例如,如果不存在FacebookToken,并且电子邮件出现了问题(电子邮件无效"),而不是"/facebookToken path not found"(通用的错误).

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.

推荐答案

您可以使用以下技巧:

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"))))

如果主阅读器失败,则可以返回自定义JsError.

You can return a custom JsError if the main reader fail.

这篇关于播放Framework JSON Reader和自定义JSError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆