用于地图的 ReactiveMongo BSONHandler
ReactiveMongo BSONHandler for Map
我有以下 class,并希望使用 reactivemongo.bson.Macros.handler
自动获取 reader 和编写器。
case class Data(a: String, b: Map[String, String])
object Data {
implicit val dataHandler = reactivemongo.bson.Macros.handler[Data]
}
但是编译失败,提示Implicit Map[String,String] for 'value vs' not found
如何进行这项工作?我正在使用 reactivemongo_2.10 0.11.10
根据this gist,我找到了一个解决方案:
case class Data(date: String, base: String, vs: Map[String, String])
object Data {
implicit object BSONMapHandler 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)
}
}
implicit val dataHandler = reactivemongo.bson.Macros.handler[Data]
}
不知道为什么reactivemongo默认不支持
我有以下 class,并希望使用 reactivemongo.bson.Macros.handler
自动获取 reader 和编写器。
case class Data(a: String, b: Map[String, String])
object Data {
implicit val dataHandler = reactivemongo.bson.Macros.handler[Data]
}
但是编译失败,提示Implicit Map[String,String] for 'value vs' not found
如何进行这项工作?我正在使用 reactivemongo_2.10 0.11.10
根据this gist,我找到了一个解决方案:
case class Data(date: String, base: String, vs: Map[String, String])
object Data {
implicit object BSONMapHandler 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)
}
}
implicit val dataHandler = reactivemongo.bson.Macros.handler[Data]
}
不知道为什么reactivemongo默认不支持