【问题标题】:Lazy formatted recursive JSON type can't be found as implicit value无法找到延迟格式化的递归 JSON 类型作为隐式值
【发布时间】:2016-01-12 18:44:01
【问题描述】:

我正在使用 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)
        }
      }
    }
}

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

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

    • 如此简单,但我却浪费了这么多时间,非常感谢!
    猜你喜欢
    • 2015-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-02
    • 1970-01-01
    • 1970-01-01
    • 2015-06-10
    • 1970-01-01
    相关资源
    最近更新 更多