Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
import spray.json._
import reactivemongo.bson._
import scala.language.implicitConversions
trait BSONDocumentFormat[T] extends BSONDocumentReader[T] with BSONDocumentWriter[T]
object SprayBson {
implicit object BSONObjectIDJsonFormat extends JsonFormat[BSONObjectID] {
def write(id: BSONObjectID) = JsString(id.toString)
def read(value: JsValue) = value match {
case JsString(x) => BSONObjectID(x)
case x => deserializationError("Expected BSONObjectID as JsString, but got " + x)
implicit def jsObjectToBsonDocument(json: JsObject) = BSONDocument( (t._1, t._2:BSONValue)))
implicit def bsonDocumentToJsObject(bson: BSONDocument) = JsObject( (t._1, t._2:JsValue)))
implicit def jsValueToBsonValue(jsValue: JsValue): BSONValue = jsValue match {
case JsString(value) BSONString(value)
case JsNumber(num)
if (num.isValidInt) BSONInteger(num.intValue)
else if (num.isValidLong) BSONLong(num.longValue)
else BSONDouble(num.doubleValue)
case JsFalse BSONBoolean(false)
case JsTrue BSONBoolean(true)
case JsNull BSONNull
case JsArray(elems) BSONArray( t:BSONValue))
case obj: JsObject obj:BSONDocument
implicit def bsonValueToJsValue(bson: BSONValue): JsValue = bson match {
case BSONString(value) JsString(value)
case BSONDouble(value) JsNumber(value)
case BSONInteger(value) JsNumber(value)
case BSONLong(value) JsNumber(value)
case BSONBoolean(value) JsBoolean(value)
case BSONNull JsNull
case arr: BSONArray JsArray( t:JsValue))
case obj: BSONDocument obj:JsObject
implicit def rootJsonFormatToBsonDocumentFormat[T](rootJsonFormat: RootJsonFormat[T]): BSONDocumentFormat[T] = new BSONDocumentFormat[T] {
def write(t: T): BSONDocument = rootJsonFormat.write(t).asJsObject
def read(bson: BSONDocument): T = bson.convertTo[T](rootJsonFormat)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment