给出以下JSON ......
{
"recipients" : [
"user1@domain1.com", "user2@domain2.com"
],
"subject" : "My subject",
"body" : "My body"
}
...我需要验证收件人列表......以下是我的代码:
import play.api.libs.json._
import play.api.libs.functional.syntax._
import play.api.libs.json.Reads._
val js = Json.parse("""{"subject":"My subject","body":"My body", "recipients":["user1@domain1.com","user2@domain2.com"]}""")
val validateRecipients = verifyingIf((arr: JsArray) =>
arr.value.nonEmpty)(Reads.email)
val recipients: Reads[JsArray] = {
(__ \ 'recipients).json.pick[JsArray] andThen validateRecipients
}
val validateNotification = (
((__ \ 'recipients).json.copyFrom(recipients)) ~
((__ \ 'subject).json.pickBranch) ~
((__ \ 'body).json.pickBranch)
).reduce
validateNotification.reads(js).fold(
valid = { validated => JsSuccess(validated) },
invalid = { errors => JsError(errors) }
)
问题是我的验证器不起作用:
res1: Product with Serializable with play.api.libs.json.JsResult[play.api.libs.json.JsObject] = JsError(List((/recipients,List(ValidationError(error.expected.jsstring,WrappedArray())))))
我错过了什么吗?
答案 0 :(得分:1)
尝试更改您的代码:
val validateRecipients = verifyingIf((arr: JsArray) => arr.value.nonEmpty)(Reads.list(Reads.email))