0

I use reactivemongo in my Play application. My models use the property id and not _id. How can I automatically transform the object ID(_id), so that it will be mapped to the id property of my models.

Currently I write the format by hand:

implicit val adviceFormat = (
  (__ \ '_id).format[BSONObjectID] and
  (__ \ 'lang).format[Lang] and
  (__ \ 'title).format[String] and
  (__ \ 'text).format[String] and
  (__ \ 'reads).formatNullable[Seq[PeriodCounter]] and
  (__ \ 'creationDate).format[DateTime] and
  (__ \ 'updateDate).format[DateTime]
)(Advice.apply, unlift(Advice.unapply))

But I would like to write only:

implicit val adviceFormat = Json.format[Advice]

Update:

Based on the answer of trevor.reznik I have figured it out.

implicit val adviceJSONReads = __.json.update((__ \ 'id).json.copyFrom((__ \ '_id).json.pick[JsObject] )) andThen Json.reads[Advice]
implicit val adviceJSONWrites = Json.writes[Advice].transform( js => js.as[JsObject] - "id"  ++ Json.obj("_id" -> js \ "id") )
akkie
  • 2,523
  • 1
  • 20
  • 34
  • I got the writes part, but not the reads part. Can you explain the first part a bit. Especially confused about the leading __.json, is that statement standalone or inside some other function ? –  Nov 08 '13 at 15:55
  • 1
    This is the short syntax for a JsPath. This is all explained in the Play Framework documentation http://www.playframework.com/documentation/2.2.x/ScalaJsonCombinators under the point "JsPath in a nutshell". You must import play.api.libs.functional.syntax._ to use this kind of syntax. – akkie Nov 10 '13 at 09:49
  • Yep I found it like 2 mins after I posted my question. Thanks though. –  Nov 10 '13 at 20:06

1 Answers1

2

For Json writes you can do something like :

val userWrites = Json.writes[User].transform( js => js.as[JsObject] - "id"  ++ Json.obj("_id" -> js \ "id") )

But I'm not sure you can do something similar with reads.

trevor.reznik
  • 286
  • 1
  • 4