Skip to content

Instantly share code, notes, and snippets.

@ploddi
Created January 20, 2014 06:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ploddi/8515660 to your computer and use it in GitHub Desktop.
Save ploddi/8515660 to your computer and use it in GitHub Desktop.
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(json.fields.toList.map(t (t._1, t._2:BSONValue)))
implicit def bsonDocumentToJsObject(bson: BSONDocument) = JsObject(bson.elements.toList.map(t (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(elems.map(t 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(arr.values.toList.map(t 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