Skip to content

Instantly share code, notes, and snippets.

@duanebester
Last active December 11, 2015 21:04
Show Gist options
  • Save duanebester/c6266f56fa2d36bcd1d1 to your computer and use it in GitHub Desktop.
Save duanebester/c6266f56fa2d36bcd1d1 to your computer and use it in GitHub Desktop.
Spray Json to Reactive Mongo ObjectId
import spray.json.DefaultJsonProtocol
/**
* Created by duane on 12/11/2015.
*/
trait ObjectIdSerialization extends DefaultJsonProtocol {
import reactivemongo.bson.BSONObjectID
import spray.json._
val objectIDRegEx = "^[0-9a-fA-F]{24}$".r
def isObjectIDValid(input: String): Boolean = (objectIDRegEx findFirstIn input).nonEmpty
implicit object ObjectIdJsonFormat extends RootJsonFormat[BSONObjectID] {
def write(iod: BSONObjectID): JsValue = {
new JsString(iod.stringify)
}
def read(jsValue: JsValue): BSONObjectID = {
jsValue match {
case JsString(oid) =>
if(isObjectIDValid(oid)){
BSONObjectID(oid)
} else {
throw new DeserializationException(s"[$oid] is not a valid ObjectID")
}
case _ =>
throw new DeserializationException("String expected")
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment