下面是一个包含用户信息的简单案例类:
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
以便在反序列化时调用密码哈希?
答案 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)
但请注意,这意味着您的Reads
和Writes
不再相互反转。