Question

I'm trying to wrap the spray-json parser such that it returns an Option rather than throws an exception.

As a first step I'm just trying to wrap the method with my own, but I'm having problems making it generic.

The parser uses an implicit format object (which is defined for the concrete type I'm using) but when the method is generic the compiler complains:

[error]     Cannot find JsonReader or JsonFormat type class for T
[error]     def parse[T](s: String): T = JsonParser(s).convertTo[T]

Here's the relevant code:

case class Person(name: String)

object Protocols {
  implicit val personFormat = jsonFormat1(Person)
}

import spray.json._

object Parser {
  import com.rsslldnphy.json.Protocols._
  // JsonParser(s).convertTo[Person] works fine, but..
  def parse[T](s: String): T = JsonParser(s).convertTo[T]  // .. doesn't
}  

What do I need to do to get this to work?

Was it helpful?

Solution

You need to pass the required implicit value, which can conveniently be done using the "context bound" shortcut notation:

def parse[T : JsonReader](s: String): T =
  JsonParser(s).convertTo[T]

This is equivalent to:

def parse[T](s: String)(implicit reader: JsonReader[T]): T =
  JsonParser(s).convertTo[T]

See What is a "context bound" in Scala?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top