Search code examples
scalaspray-json

Spray Json: Convert a Generic type to JsonFormat


I have a class similar to Pairs. I have a trait that converts this Pairs class to Json format.

import scala.reflect.ClassTag
import spray.json._
import spray.json.DefaultJsonProtocol

case class Pairs[K, V](key:K, value: V)

trait Convertor[K, V] extends DefaultJsonProtocol{
  implicit val convertor = jsonFormat2(Pairs[K, V])
}
val p = Pairs[String, Int]("One", 1)
println(p.toJson)

When I use this trait I get following error to have a convertor for K and V types.

error: could not find implicit value for evidence parameter of type Convertor.this.JF[K] implicit val convertor = jsonFormat2(Pairs[K, V]) ^

But how can I have bring generic data type in scope. Anyone can help me?


Solution

  • You need to provide JsonFormat for both key type and value type.

    This code

    import spray.json.DefaultJsonProtocol._
    import spray.json._
    case class Pairs[K, V](key: K, value: V)
    implicit def pairsFormat[K: JsonFormat, V: JsonFormat] = jsonFormat2(Pairs.apply[K, V])
    val p = Pairs[String, Int]("One", 1)
    println(p.toJson)
    

    will print

    {"key":"One","value":1}