问题
Just trying out the spray-json, and it seems to be having problem finding my JsonProtocols I have setup. I have the following dependencies:
"io.spray" % "spray-servlet" % "1.2-M8",
"io.spray" % "spray-routing" % "1.2-M8",
"io.spray" % "spray-testkit" % "1.2-M8",
"io.spray" % "spray-json_2.10" % "1.2.5"
And the following code:
Content.scala
import spray.json.DefaultJsonProtocol
case class Content(id:String, name: String, contentType: String, duration: Int)
object MyJsonProtocol extends DefaultJsonProtocol {
implicit val contentFormat = jsonFormat4(Content)
}
I get an error on the line where I'm returning Content
in the complete {}
block, the error is as follows and the code is below it:
Description Resource Path Location Type could not find implicit value for evidence parameter of type spray.httpx.marshalling.Marshaller[Content] MyService.scala line 32 Scala Problem
import akka.actor.Actor
import spray.routing._
import spray.http._
import MediaTypes._
import spray.json.DefaultJsonProtocol
import Content
import MyJsonProtocol._
class MyServiceActor extends Actor with MyService{
def actorRefFactory = context
def receive = runRoute(myRoute)
}
trait MyService extends HttpService {
val myRoute =
path("") {
get {
respondWithMediaType(`application/json`) { // XML is marshalled to `text/xml` by default, so we simply override here
complete {
new Content("1234", "Some Content", "YT", 60)
}
}
}
}
}
Can anyone see anything wrong? This is literally the spray-template code with the spray-json stuff sprinkled in
回答1:
Json marshaller is in SprayJsonSupport trait, so just import it into the scope:
import spray.httpx.SprayJsonSupport._
And with this marshaller you can remove respondWithMediaType(application/json)
directive, cause it Json is marshaled only to application/json
media type:
implicit def sprayJsonMarshaller[T](implicit writer: RootJsonWriter[T], printer: JsonPrinter = PrettyPrinter) =
Marshaller.delegate[T, String](ContentTypes.`application/json`) { value ⇒
val json = writer.write(value)
printer(json)
}
来源:https://stackoverflow.com/questions/18371835/marshaller-not-found