处理非默认嵌套 Json 读取

Handling non-default nested Json Reads

所以我有以下 JSON:

{
  "senderEmail" : "sender@email.com",
  "recipientEmails" : ["first@email.com", "second@email.com"]
}

并想将其映射到案例 class:

case class Payload (senderEmail: String, recipientEmails: Seq[String])

使用 Play 的 Json 使用电子邮件验证器读取。

虽然对于 senderEmail 来说微不足道,但我在使用 recipientEmails 时遇到了麻烦,因为它既是 Seq 又是电子邮件,所以这 而不是 工作:

implicit val payloadRead: Reads[Payload] = (
    (JsPath \ "senderEmail").read[String](Reads.email) and
    (JsPath \ "recipientEmails").read[Seq[String]](Reads.seq))(Payload.apply _)

我得到 overloaded method value read with alternatives

那么我怎样才能将 Reads.seq 和 Reads.email 结合起来呢?

保持简单...

scala> import play.api.libs.json._

scala> import play.api.libs.functional.syntax._

scala> case class Payload (senderEmail: String, recipientEmails: Seq[String])
defined class Payload

scala> implicit val reads: Reads[Payload] = (
     |   (JsPath \ "senderEmail").read(Reads.email) and
     |   (JsPath \ "recipientEmails").read(Reads.seq(Reads.email))
     | )(Payload.apply _)
reads: play.api.libs.json.Reads[Payload] = play.api.libs.json.Reads$$...

scala> Json.parse("""{
     |   "senderEmail" : "sender@email.com",
     |   "recipientEmails" : ["first@email.com", "second@email.com"]
     | }""").validate[Payload]
res0: play.api.libs.json.JsResult[Payload] = JsSuccess(Payload(sender@email.com,Vector(first@email.com, second@email.com)),)