使用Scala中的PlayFramework进行Json验证

时间:2014-10-06 11:01:50

标签: 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.apply,unlift(Person.unapply))

显然,FormatNullable不能与ReadConstraints一起使用,我该如何解决这个问题呢?

1 个答案:

答案 0 :(得分:0)

emailRead[String],而您需要Format[String]。对于对称的情况,FormatReadWrite的组合。这不是这种情况,因为验证仅用于读取JSON,而不是用于编写JSON。所以你不能写一个Format

要解决此问题,请分别写下ReadWrite

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)