Search code examples
scalaimplicittraitsspray-json

spray-json: Serialize a generic trait


spray-json relies on the presence of an in-scope, implicit JsonWriter[T] when calling toJson on an instance of T.

Say I have a trait with several concrete subtypes, each of which has a JsonWriter:

trait Base
case class Foo(a: Int) extends Base
case class Bar(a: Int, b: Int) extends Base
implicit val FooFormat = jsonFormat1(Foo)
implicit val BarFormat = jsonFormat2(Bar)

def go(o: Base) = {
    o.toJson
}

go doesn't compile because there's no JsonWriter for Base, even though there are writers for all of the concrete subtypes.

How can I reorganize this code such that generic functions of Base use the appropriate json formatters?


Solution

  • You can use a generic method with type and context bounds. Like this:

    def go[T <: Base : JsonWriter](t: T) = t.toJson