【发布时间】:2015-10-23 19:15:20
【问题描述】:
我有一个隐式的 Json 读写如下:
implicit val userJsonWrites = new Writes[User] {
override def writes(user: User): JsValue = Json.obj(
idKey -> Json.toJson(user._id),
firstNameKey -> Json.toJson(user.firstName),
lastNameKey -> Json.toJson(user.lastName),
emailKey -> Json.toJson(user.email),
//passKey -> Json.toJson(user.pass),
addressKey -> Json.toJson(user.address),
createDateKey -> Json.toJson(user.createDate),
activateDateKey -> Json.toJson(user.activateDate),
isUserActivatedKey -> Json.toJson(user.isUserActivated),
verificationDateKey -> Json.toJson(user.verificationDate)
)
}
implicit val userJsonReads = new Reads[User] {
override def reads(json: JsValue): JsResult[User] = {
val user = User(
_id = (json \ idKey).as[Option[String]],
firstName = (json \ firstNameKey).as[String],
lastName = (json \ lastNameKey).as[String],
email = (json \ emailKey).as[String],
pass = (json \ passKey).as[String],
address = (json \ addressKey).as[Address],
createDate = (json \ createDateKey).as[DateTime],
activateDate = (json \ activateDateKey).as[Option[DateTime]],
verificationDate = (json \ verificationDateKey).as[Option[DateTime]],
isUserActivated = (json \ isUserActivatedKey).as[Boolean]
)
JsSuccess(user)
}
}
编译时出现以下错误:
Error:(84, 32) not enough arguments for method as: (implicit fjs: play.api.libs.json.Reads[Option[String]])Option[String].
Unspecified value parameter fjs.
_id = (json \ idKey).as[Option[String]],
^
Error:(84, 32) No Json deserializer found for type Option[String]. Try to implement an implicit Reads or Format for this type.
_id = (json \ idKey).as[Option[String]],
^
我的用户对象如下所示:
case class User(
_id: Option[String],
createDate: DateTime,
activateDate: Option[DateTime],
verificationDate: Option[DateTime],
email: String,
pass: String,
firstName: String,
lastName: String,
isUserActivated: Boolean,
address: Address
)
_id 实际上是 MongoDB 的 ObjectId,我必须将其作为选项!
【问题讨论】:
-
您应该研究 JSON 组合子,而不是尝试像那样编写读/写。这种方法非常脆弱和无情。
-
你能举个例子吗?
-
我对 JSON 组合器不满意。对于 JSON 转换,我想保持简单,而不需要太多 Scala 或 Play 框架的糟糕酷炫,这似乎有点过头了!
-
您的 20 - 30 行代码远非简单。不仅如此,它还会在第一个错误时*抛出异常*!使用组合器,您可以安全地聚合所有验证错误。
标签: json scala playframework