我有一个使用Salat的mongodb集合的scala类。我试图在我的测试用例中将 json 字符串反序列化为对象。但是,它会引发有关日期类型格式的异常。它使用 Salat DAO 获取对象时运行良好。但是当我测试它时,它给了我一个错误。
蒙戈集合的类
case class MemberData(
id: ObjectId = new ObjectId,
memberId: String,
anotherDate: Date = new Date()
)
object MemberData extends MemberDataDAO with MemberDataJson
trait MemberDataDAO extends ModelCompanion[MemberData, ObjectId] {
def collection = mongoCollection("member_data")
val dao = new SalatDAO[MemberData, ObjectId](collection) {}
}
trait MemberDataJson {
implicit val memberDataJsonWrite = (
(__ "id").write[ObjectId] ~
(__ "memberId").write[String] ~
(__ "anotherDate").write[Date](Writes.dateWrites("yyyy-MM-dd HH:mm:ss"))
)(unlift(MemberData.unapply))
implicit val memberDataJsonRead = (
(__ 'id).read[ObjectId] ~
(__ 'memberId).read[String] ~
(__ 'anotherDate).read[Date](Reads.dateReads("yyyy-MM-dd HH:mm:ss")).orElse(Reads.pure(new Date()))
)(MemberData.apply _)
}
测试用例失败:
val memberDataJsObj = Json.obj(
"id" -> _id.toString,
"memberId" -> "1",
"anotherDate" -> updateDateStr
)
val toJsonStr = Json.stringify(memberDataJsObj)
assert(MemberData.fromJSON(toJsonStr) == memberData)
原因:
! Invalid format: "2014-02-07 09:27:21" is malformed at " 09:27:21"
您需要将Context#jsonConfig#dateStrategy
配置为使用指定要反序列化的日期的文本格式的StringDateStrategy
,"yyyy-MM-dd HH:mm:ss"
。