Skip to content

Instantly share code, notes, and snippets.

@ntbrock
Created October 17, 2018 20:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ntbrock/556a1add78dc287b0cf7e0ce45c743c1 to your computer and use it in GitHub Desktop.
Save ntbrock/556a1add78dc287b0cf7e0ce45c743c1 to your computer and use it in GitHub Desktop.
Play Framework 2.6 Mongo Scala Driver Official Json Format Macro for ObjectId
import org.mongodb.scala.bson.ObjectId
import play.api.libs.json._
import scala.util.Try
object ObjectIdFormatJsonMacro extends Format[ObjectId] {
def writes(objectId: ObjectId): JsValue = JsString(objectId.toString)
def reads(json: JsValue): JsResult[ObjectId] = json match {
case JsString(x) => {
val maybeOID: Try[ObjectId] = Try{new ObjectId(x)}
if(maybeOID.isSuccess) JsSuccess(maybeOID.get) else {
JsError("Expected ObjectId as JsString")
}
}
case _ => JsError("Expected ObjectId as JsString")
}
}
@ntbrock
Copy link
Author

ntbrock commented Oct 17, 2018

Use it like this in your business object:

case class BusinessTime(_id: ObjectId = new ObjectId(), payRate: Double)

object BusinessTime {
implicit val objectIdFormat = ObjectIdFormatJsonMacro
implicit val businessTimeFormat = Json.format[BusinessTime]
}

@ntbrock
Copy link
Author

ntbrock commented Oct 18, 2018

RIP ReactiveMongo, codecs ftw

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment