Marshaller没找到

时间:2013-08-22 04:42:51

标签: scala spray-json

刚刚尝试使用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)
}

我在Content块中返回complete {}的行上出现错误,错误如下,代码位于其下方:

  

描述资源路径位置类型   找不到类型为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)
          }
        }
      }
    }
}

任何人都可以看到任何错误吗?这实际上是喷涂模板代码,其中喷涂了喷涂json的东西

1 个答案:

答案 0 :(得分:7)

Json marshaller在SprayJsonSupport特性中,所以只需将其导入范围:

import spray.httpx.SprayJsonSupport._

使用此marshaller,您可以删除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)
  }