eigengo / scalad

Scala Data access for NoSQL databases
47 stars 15 forks source link

SprayJSONSerialisers #13

Closed fommil closed 11 years ago

fommil commented 11 years ago

This is from today's code review of

https://github.com/adinapoli/scalad/commit/ce1b8344f8ecd29e55e8b8a46159275a69cba9cb

(it is also useful to refactor this functionality as implicits)

object SprayJsonImplicits {

  def js2db(jsValue: JsValue): Object = {
    import scala.collection.JavaConversions.mapAsJavaMap
    import scala.collection.JavaConversions.seqAsJavaList

    jsValue match {
      case JsString(s) => s // do some magic with mixins for special forms (UUID, Date, etc)
      case JsNumber(n) => n
      case JsNull => None
      case JsBoolean(b) => Boolean.box(b)
      case a: JsArray => {
        val list = new BasicDBList()
        list.addAll(a.elements.map(f => js2db(f)))
        list
      }
      case o: JsObject =>  new BasicDBObject(o.fields.map(f => (f._1, js2db(f._2))).toMap)
    }
  }

  implicit val SprayJsonToDBObject = (jsValue: JsValue) => js2db(jsValue).asInstanceOf[DBObject]

  implicit val SprayStringToDBObject = (json: String) => js2db(JsonParser.apply(json))
}

then the serialiser becomes trivial

  import SprayJsonImplicits._

  override def serialize(entity: T): DBObject = {
    formatter.write(entity)
  }

  def formatter = implicitly[JsonFormat[T]]
fommil commented 11 years ago

oh and WrapAsJava is now the preference to JavaConversions

fommil commented 11 years ago

Also, make sure the None bit is tested – that's a Scalaism and may not convert into the Java land of DBObject.