1

只是尝试一下 spray-json,似乎在找到我设置的 JsonProtocols 时遇到了问题。我有以下依赖项:

"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"

以及以下代码:

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)
}

Contentcomplete {}块中返回的行出现错误,错误如下,代码在其下方:

描述资源路径位置类型找不到类型spray.httpx.marshalling.Marshaller [Content] MyService.scala第32行Scala问题的证据参数的隐式值

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)
          }
        }
      }
    }
}

有人能看出有什么不对吗?这实际上是带有spray-json内容的spray-template代码

4

1 回答 1

7

Json marshaller 在 SprayJsonSupport trait 中,因此只需将其导入范围:

import spray.httpx.SprayJsonSupport._

使用这个编组器,您可以删除respondWithMediaType(application/json)指令,因为它 Json 仅被编组为application/json媒体类型:

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)
  }
于 2013-08-22T07:24:12.423 回答