Created
October 17, 2018 20:11
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") | |
} | |
} |
RIP ReactiveMongo, codecs ftw
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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]
}