case class User(id: Int, name: String, birth: java.util.Date)
object User {
implicit object UserWrites extends OWrites[User] {
def writes(user: User): JsObject = Json.obj(
"_id" -> user.id,
"name" -> user.name,
// the implicit conversion for Date will be converted to epoch long (NumberLong in Mongo)
"birth" -> user.birth
)
}
implicit object UserReads extends Reads[User] {
def reads(json: JsValue): JsResult[User] = json match {
case obj: JsObject => try {
val id = (obj \ "_id").as[Int]
val name = (obj \ "name").as[String]
// assuming 'birth' is stored in mongo as a ISODate, we wouldn't be able to read a Date directly
// since the JsObject got here is JsObject("$date": $the_epoch_long).
val birth = (obj \ "birth").as[java.util.Date]
JsSuccess(User(id, name, birth))
} catch {
case e: Exception => JsError(e.getStackTraceString)
}
case _ => JsError("error!")
}
}
}
What do you mean by "in ReactiveMongo, a java.util.Date will be written as a NumberLong"? See https://github.com/ReactiveMongo/ReactiveMongo/blob/master/bson/src/test/scala/Handlers.scala#L126
--
You received this message because you are subscribed to a topic in the Google Groups "ReactiveMongo - http://reactivemongo.org" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/reactivemongo/YsFKUHMt0DY/unsubscribe.
To unsubscribe from this group and all its topics, send an email to reactivemong...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
"birth" -> BSONDateTime(user.birth.getTime)
val birth = new java.util.Date((obj \ "birth").as[BSONDateTime].value)
What's the issue there?
--
You received this message because you are subscribed to a topic in the Google Groups "ReactiveMongo - http://reactivemongo.org" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/reactivemongo/YsFKUHMt0DY/unsubscribe.
To unsubscribe from this group and all its topics, send an email to reactivemong...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.