Scala无法反序列化java.util.date格式

时间:2014-02-07 18:07:39

标签: json mongodb scala playframework-2.2 salat

我有一个使用Salat的mongodb集合的scala类。我尝试在我的测试用例中将json字符串反序列化为对象。但是,它会引发关于日期类型格式的异常。使用Salat DAO可以很好地获取对象。但是当我测试它时,它给了我一个错误。

mongo集合的类

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"

1 个答案:

答案 0 :(得分:1)

您需要将Context#jsonConfig#dateStrategy配置为使用StringDateStrategy来指定要反序列化的日期的文本格式"yyyy-MM-dd HH:mm:ss"