2
votes

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?

2

2 Answers

6
votes

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}
1
votes

K and V could be everything (Any). As you don't have for everything a Convertor, you have to restrict K and V.

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

Now you need to provide Converters for PairKey and PairValue and all its children.

You find infos here: spray-json#jsonprotocol