播放:如何在反序列化Json时修改数据

时间:2014-01-07 15:54:50

标签: json scala playframework

下面是一个包含用户信息的简单案例类:

import play.api.libs.json._
import play.api.libs.functional.syntax._

case class User(
  val username: String,
  val password: String
)

...这里是一个配套对象,它提供了将User对象序列化/反序列化为JSON的功能:

object User {

  implicit val userWrites: Writes[User] = (
    (__ \ 'username).write[String] ~
    (__ \ 'password).write[String]
  )(unlift(User.unapply))

  implict val userReads: Reads[User] = (
    (__ \ 'username).read[String] ~
    (__ \ 'password).read[String] // how do I invoke the password hasher here?
  )(User.apply(_, _))
}

假设User个对象应始终包含散列密码,但传入的JSON始终提供明文...如何增强Reads以便在反序列化时调用密码哈希?

1 个答案:

答案 0 :(得分:2)

您可以在map上使用Reads方法:

def doSomething(s: String) = s * 3

case class User(val username: String, val password: String)

object User {
  implicit val userWrites: Writes[User] = (
    (__ \ 'username).write[String] ~
    (__ \ 'password).write[String]
  )(unlift(User.unapply))

  implicit val userReads: Reads[User] = (
    (__ \ 'username).read[String] ~
    (__ \ 'password).read[String].map(doSomething)
  )(User.apply(_, _))
}

然后:

scala> Json.parse("""{"username": "foo", "password": "bar"}""").as[User]
res0: User = User(foo,barbarbar)

但请注意,这意味着您的ReadsWrites不再相互反转。