[spray-json] Cannot deserialize a generic collection

253 views
Skip to first unread message

Anatoly Rabinovich

unread,
Dec 10, 2015, 9:12:50 AM12/10/15
to spray.io User List
Hi,

I'm trying to deserialize a json string into a generic collection.

My code looks something like this:
class MyClass(json: String) {
def collectionType1: Set[Type1] = loadElements[Type1]

def collectionType2: Set[Type2] = ???

private def loadElements[T]: Set[T] = {
json.parseJson.convertTo[Set[T]]
}
}


I also have the following defined (I have the exact same definition for 'Type2', the case class looks different):
case class Type1(p1: String, p2: String)

object Type1JsonProtocol extends DefaultJsonProtocol {
private implicit val collectionType1Format = jsonFormat2(Type1)

implicit object Type1SetJsonReader extends JsonReader[Set[Type1]] {
override def read(json: JsValue): Set[Country] = json match {
case JsArray(elements) => elements.map(_.convertTo[Type1]) toSet
case x => deserializationError("Expected Collection as JsArray, but got " + x)
}
}
}

When compiling the code, I get the following error:
Error:(25, 29) Cannot find JsonReader or JsonFormat type class for Set[T]
    val res = json.convertTo[Set[T]]
                            ^
and:
Error:(25, 29) not enough arguments for method convertTo: (implicit evidence$1: spray.json.JsonReader[Set[T]])Set[T].
Unspecified value parameter evidence$1.
    val res = json.convertTo[Set[T]]
                            ^
I'm obviously missing something, but have a feeling it's something small. Does anyone have any clue?

Thanks!

Anatoly Rabinovich

unread,
Dec 10, 2015, 9:17:03 AM12/10/15
to spray.io User List
Reply all
Reply to author
Forward
0 new messages