I have a scala class for a mongodb collection using Salat. I tried to deserialize json string to object in my test case. However, it throws an exception about the format of date type. It runs fine in getting the object using Salat DAO. But when I tested it, it gave me an error.
Class for a mongo collection
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 _)
}
Testcase Failed:
val memberDataJsObj = Json.obj(
"id" -> _id.toString,
"memberId" -> "1",
"anotherDate" -> updateDateStr
)
val toJsonStr = Json.stringify(memberDataJsObj)
assert(MemberData.fromJSON(toJsonStr) == memberData)
Reason:
! Invalid format: "2014-02-07 09:27:21" is malformed at " 09:27:21"
you need to configure your Context#jsonConfig#dateStrategy
to use a StringDateStrategy
which specifies the text format of the dates you want to deserialize, "yyyy-MM-dd HH:mm:ss"
.