处理非默认的嵌套Json读取

时间:2019-05-26 08:34:09

标签: json scala playframework play-json

所以我有以下JSON:

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

,并希望将其映射到案例类:

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

使用带有电子邮件验证程序的Play的Json Reads。

虽然对于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结合在一起?

1 个答案:

答案 0 :(得分:4)

只需保持简单...

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