所以我有以下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结合在一起?
答案 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)),)