Scala中PlayFramework的Json验证
有人能帮我修复以下代码吗Scala中PlayFramework的Json验证,scala,playframework,playframework-2.3,Scala,Playframework,Playframework 2.3,有人能帮我修复以下代码吗 case class Person(name:String,email:Option[String]) implicit val personFormat:Format[Person] = ( (__ \ "name").format[String] ~ (__ \ "email").formatNullable[String](email) // The code doesn't compile here )(Person.a
case class Person(name:String,email:Option[String])
implicit val personFormat:Format[Person] = (
(__ \ "name").format[String] ~
(__ \ "email").formatNullable[String](email) // The code doesn't compile here
)(Person.apply,unlift(Person.unapply))
显然FormatNullable不适用于ReadConstraints,我如何解决这个问题?
电子邮件是一个读取[String]
,而您需要一个格式[String]
<代码>格式
是读取
和写入
的组合,适用于对称的情况。这里的情况并非如此,因为验证只用于读取JSON,而不用于编写JSON。因此,您不能编写单一的格式
要解决此问题,请分别编写您的Read
和write
:
implicit val personReads: Reads[Person] = (
(JsPath \ "name").read[String] ~
(JsPath \ "email").readNullable[String](email)
)(Person.apply _)
implicit val personWrites: Writes[Person] = (
(JsPath \ "name").write[String] ~
(JsPath \ "email").writeNullable[String]
)(unlift(Person.unapply))
implicit val personFormat: Format[Person] =
Format(personReads,personWrites)
谢谢Martin,实际上我注意到当我将formatNullable[String](电子邮件)更改为format[String](电子邮件)时,它可以工作。只有当我使用formatNullable时,它才会停止工作。啊,好吧,那就与文档相矛盾了D我相信他们可能为了方便起见在
格式中添加了这种可能性,但忘记了将其添加到格式为空的。但这只是一个猜测。我也这么认为,我会接受答案。谢谢