Transforming ReactiveMongo JSON with Play JSON

33 Views Asked by At

ReactiveMongo's JSON functionality generates objects (JsObject in play-json parlance) rather than scalars for certain MongoDB datatypes like BSONObjectID and BSONDateTime. For example, you get JSON like this:

{
   "_id" : {
      "$oid" : "5de32e618f02001d8d521757"  //BSONObjectID
   },
   "createdAt" : {
      "$date" : 15751396221447 //BSONDateTime
   }
}

Aside from being cumbersome to deal with, I would prefer not to expose JSON that leaks MongoDB concerns to REST clients.

The tricky thing is that these values occur throughout the tree, so I need to write a Play JSON transformer smart enough to recursively transform the above at every level to look like this:

{
   "id" : "5de32e618f02001d8d521757",
   "createdAt" : 15751396221447 
}

One failed attempt to do this for just BSONObjectID is this:

(JsPath \ "_id").json.update(
    JsPath.read[JsObject].map{ o => o ++ Json.obj( "id" -> (o \ f"$$oid").as[String]) }
)

How can I do this?

0

There are 0 best solutions below