无法将惰性格式的递归JSON类型视为隐式值

时间:2015-10-14 15:23:17

标签: json scala spray spray-json spray-routing

我正在使用Spray构建REST API。 我的一种JSON数据类型是递归的:

case class Container(id: String,
                 name: String,
                 read_only: Boolean,
                 containers: List[Container],
                 content: List[Content])

object PeriusJsonProtocol extends DefaultJsonProtocol {
  implicit val contentFormat = jsonFormat8(Content)
  implicit val containerFormat: JsonFormat[Container] = lazyFormat(jsonFormat5(Container))
}

在HttpService中完成路由时,我收到以下错误:

Error:(49, 18) could not find implicit value for parameter um: spray.httpx.unmarshalling.FromRequestUnmarshaller[Container]
        entity(as[Container]) { container =>
                 ^

Error:(49, 18) not enough arguments for method as: (implicit um: spray.httpx.unmarshalling.FromRequestUnmarshaller[Container])spray.httpx.unmarshalling.FromRequestUnmarshaller[Container].
Unspecified value parameter um.
        entity(as[Container]) { container =>
                 ^

HttpService看起来像这样:

import akka.actor.Actor
import spray.routing._
import spray.httpx.SprayJsonSupport._

import PeriusJsonProtocol._

class RestServiceActor extends Actor with RestService {
  def actorRefFactory = context
  def receive = runRoute(projectsRoute)
}

// this trait defines our service behavior independently from the service actor
trait RestService extends HttpService {
  private val PROJECTS  = "projects"

  val projectsRoute =
    path(PROJECTS) {
      get {
        complete(MongoUtil.getAll(PROJECTS, META) map ContainerMap.fromBson)
        //complete(Container("test", "name", false, List(), List()))
      } ~ post {
        entity(as[Container]) { 
          //complete(MongoUtil.insertProject(container))
          complete(container)
        }
      }
    }
}

complete中的GET有效,即使该函数返回容器列表。 get中注释掉的行不起作用,但它无法隐式转换post中的Container,如错误消息中所示。我该怎么做才能使容器隐式工作并仍然保持其递归结构?

1 个答案:

答案 0 :(得分:6)

Container类是根级别json,因此您需要将相应的隐式更改为:

implicit val containerFormat: RootJsonFormat[Container] = rootFormat(lazyFormat(jsonFormat5(Container)))