Bson Handler for SortedSet[(Int,V)]

21 views
Skip to first unread message

Hassene Ben Amara

unread,
Apr 12, 2017, 11:51:19 AM4/12/17
to ReactiveMongo - http://reactivemongo.org
Hi All,

I am trying to write a bson handler for a SortedSet of tuples (SortedSet[(Int, V)]. 

I created the handler for V and is within the scope. Also, created the following handler for the Set like below but the compiler is still compalaining about bsonHandler not found for the SortedSet field. Can anyone help?

Thank you!

implicit def SetReader[V, B <: BSONValue](implicit vr: BSONReader[B, V]) = new BSONDocumentReader[immutable.Set[(Int, V)]] {
def read(bson: BSONDocument): immutable.Set[(Int, V)] = {
val elements = bson.elements.map { tuple =>
tuple.name.toInt -> tuple.value.seeAsTry(vr).get
}
elements.toSet
}
}

implicit def SetWriter[V, B <: BSONValue](implicit vw: BSONWriter[V, B]) = new BSONDocumentWriter[SortedSet[(Int, V)]] {
def write(set: SortedSet[(Int, V)]): BSONDocument = {
val elements = set.toStream.map { tuple =>
tuple._1 -> vw.write(tuple._2)
}
BSONDocument(elements)
}
}

Cédric Chantepie

unread,
Apr 12, 2017, 6:12:02 PM4/12/17
to ReactiveMongo - http://reactivemongo.org
Please be more specific. SortedSet is properly supported:

scala> implicitly[reactivemongo.bson.BSONReader[reactivemongo.bson.BSONArray, SortedSet[String]]]
res1
: reactivemongo.bson.BSONReader[reactivemongo.bson.BSONArray,scala.collection.immutable.SortedSet[String]] = reactivemongo.bson.DefaultBSONHandlers$BSONArrayCollectionReader@72b4af6c


Hassene Ben Amara

unread,
Apr 12, 2017, 6:22:03 PM4/12/17
to ReactiveMongo - http://reactivemongo.org
Hi Cedric,

Thanks for your prompt answer. I am trying to serialize a SortedSet of Tuple:

This is the field I am trying to serialize:
buffer: SortedSet[(Int, TraitType)] = SortedSet.empty[(Int, TraitType)](Ordering.by(_._1))

and I have the Bson handler for TraitType (just a simple trait with 2 int val):
implicit object TraitTypeHandler extends BSONHandler[BSONDocument, TraitTypeHandler] {
def write(message: TraitTypeHandler) = BsonSerializer serialize message
def read(bson: BSONDocument) = (BsonSerializer deserialize bson).asInstanceOf[TraitTypeHandler]
}

But the compiler still throw:
Error:(83, 54) Implicit reactivemongo.bson.BSONReader[scala.collection.immutable.SortedSet] not found for 'buffer'
   

Any idea please?

Thanks,

Cédric Chantepie

unread,
Apr 13, 2017, 4:06:46 PM4/13/17
to ReactiveMongo - http://reactivemongo.org
There is no default codec for such tuple, as there is no common BSON representation for.
Reply all
Reply to author
Forward
0 new messages