Skip to content

Instantly share code, notes, and snippets.

@dbalduini
Last active August 29, 2015 14:17
Show Gist options
  • Save dbalduini/c772e54c9a9ea4e17152 to your computer and use it in GitHub Desktop.
Save dbalduini/c772e54c9a9ea4e17152 to your computer and use it in GitHub Desktop.
ReactiveMongo BSON Handler for scala Map
sealed trait LowPriorityMapHandlers {
/*
* Item => Map("A" -> "1", "B" -> "2", "C" -> "3")
* Json => { "A": "1", "B": "2", "C": "3"}
*/
implicit object BSONMapHandler1 extends BSONHandler[BSONDocument, Map[String, String]] {
override def read(bson: BSONDocument): Map[String, String] = {
bson.elements.map {
case (key, value) => key -> value.asInstanceOf[BSONString].value
}.toMap
}
override def write(t: Map[String, String]): BSONDocument = {
val stream: Stream[Try[(String, BSONString)]] = t.map {
case (key, value) => Try((key, BSONString(value)))
}.toStream
BSONDocument(stream)
}
}
/*
* Item => Map(1 -> 1.0, 2 -> 2.0, 3 -> 3.0)
* Json => [[1,1.0], [2,2.0], [3,3.0]]
*/
implicit object BSONMapHandler2 extends BSONHandler[BSONValue, Map[Int, Double]] {
override def read(bson: BSONValue): Map[Int, Double] = {
val t = bson.seeAsTry[BSONArray] map { arr =>
arr.values.map { tuple =>
val tuple2 = tuple.asInstanceOf[BSONArray]
val k = tuple2.getAs[Int](0).get
val v = tuple2.getAs[Double](1).get
k -> v
}.toMap
}
t.get
}
override def write(t: Map[Int, Double]): BSONValue = {
val elements: List[List[BSONValue]] = t.toList.map {
case (key, value) => List(BSONInteger(key), BSONDouble(value))
}
BSON.write(elements)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment