Last active
December 11, 2015 21:04
-
-
Save duanebester/c6266f56fa2d36bcd1d1 to your computer and use it in GitHub Desktop.
Spray Json to Reactive Mongo ObjectId
This file contains hidden or 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 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