Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala中PlayFramework的Json验证_Scala_Playframework_Playframework 2.3 - Fatal编程技术网

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我相信他们可能为了方便起见在
格式中添加了这种可能性,但忘记了将其添加到
格式为空的
。但这只是一个猜测。我也这么认为,我会接受答案。谢谢