How to deserialize dates as ZonedDateTime? [Play]

180 views
Skip to first unread message

Heikki Salokanto

unread,
Sep 20, 2017, 9:48:55 AM9/20/17
to ReactiveMongo - http://reactivemongo.org
I've got a typical case class with a date-time field, like this:

case class Foo(a: String, b: Int, c: Option[Seq[String]], datetime: ZonedDateTime)

Date-times are stored in Mongo as ISODate, i.e. in {"$date": "2017-09-19T10:11:22Z"} format.

Trying to find() these objects, I get:

Caused by: play.api.libs.json.JsResultException:
JsResultException(errors:List((/timestamp,List(ValidationError(List(error.expected.date),WrappedArray())))))
at reactivemongo.play.json.JSONSerializationPack$.deserialize(package.scala:729)
at reactivemongo.play.json.JSONSerializationPack$.deserialize(package.scala:703)
at reactivemongo.api.SerializationPack$class.readAndDeserialize(serializationpack.scala:30)
at reactivemongo.play.json.JSONSerializationPack$.readAndDeserialize(package.scala:703)
at reactivemongo.core.protocol.ReplyDocumentIterator$$anon$1.next(protocol.scala:413)
at reactivemongo.api.DefaultCursor$Impl$$anonfun$6.apply(cursor.scala:629)
at scala.util.Try$.apply(Try.scala:192)
at reactivemongo.api.DefaultCursor$Impl$class.go$1(cursor.scala:629)
at reactivemongo.api.DefaultCursor$Impl$$anonfun$foldWhileM$1.apply(cursor.scala:649)
at reactivemongo.api.DefaultCursor$Impl$$anonfun$foldWhileM$1.apply(cursor.scala:649)
at reactivemongo.api.DefaultCursor$Impl$$anonfun$foldBulksM$1.apply(cursor.scala:619)
at reactivemongo.api.DefaultCursor$Impl$$anonfun$foldBulksM$1.apply(cursor.scala:617)
at reactivemongo.api.FoldResponses.reactivemongo$api$FoldResponses$$handleResponse(cursor.scala:812)
at reactivemongo.api.FoldResponses$$anonfun$8.apply(cursor.scala:781)
at reactivemongo.api.FoldResponses$$anonfun$8.apply(cursor.scala:776)
at reactivemongo.api.FoldResponses$$anonfun$$bang$1.apply$mcV$sp(cursor.scala:896)
at akka.actor.Scheduler$$anon$4.run(Scheduler.scala:126)
... 6 common frames omitted

Tried adding a Reads for it, but it doesn't seem to invoke this at all -- no log message is output.

implicit val zonedDateTimeReads: Reads[ZonedDateTime] = new Reads[ZonedDateTime] {
  override def reads(json: JsValue): JsResult[ZonedDateTime] = {
    Log.warn("Reading ZonedDateTime from: " + json.toString())
    (json \ "$date").validate[Long].map(millis =>
      ZonedDateTime.ofInstant(Instant.ofEpochMilli(millis), TimeUtil.UTC))
  }
}


Play 2.5, ReactiveMongo 0.12.3, MongoDB 3.4.6, Scala 2.11.

Thanks.

Cédric Chantepie

unread,
Sep 20, 2017, 12:40:26 PM9/20/17
to ReactiveMongo - http://reactivemongo.org
The result of the println would help to reproduce.
Reply all
Reply to author
Forward
0 new messages