spray-json 递归 json 问题 - 找不到证据参数的隐式值

spray-json recursive json issue - could not find implicit value for evidence parameter

你好,我在使用 spray-json 库和递归数据结构解析 json 时有点挣扎。

我有以下案例 class 定义的结构和协议

import spray.json.DefaultJsonProtocol
import spray.json._

case class OfferAnalysisReport(BUG: DleTN, DOM: DleTN) extends AnalyticalReport
case class DleTN(doc_count: Int, result: AggsDefinition)
case class BucketDefinition(key: String, doc_count: Int, result: Option[AggsDefinition])
case class AggsDefinition(buckets: List[BucketDefinition])

object OfferAnalysisReportProtocol extends DefaultJsonProtocol {
  implicit val aggsDefFormat = lazyFormat(jsonFormat(AggsDefinition,"buckets"))

  implicit val bucketDefinitionFormat = lazyFormat(jsonFormat(BucketDefinition,"key","doc_count","result"))

  implicit val dleTypNemovitostisFormat = jsonFormat2(DleTypuNemovitosti)

  implicit val OfferAnalysisReportFormat = jsonFormat2(OfferAnalysisReport)
}

在我导入的测试中:

import spray.json._
import OfferAnalysisReportProtocol._

但我仍然得到

Error: couldn't find implicit value for evidence parameter of type BuckedDefinition.

我是不是漏掉了什么重要的东西?有人可以给我提示吗?

您必须像您所做的那样用 lazyFormat 包装您的格式构造函数,但您还必须提供一个显式类型注释,如下所示:

implicit val fooFormat: JsonFormat[Foo] = lazyFormat(jsonFormat(Foo, "i", "foo"))

来源:https://github.com/spray/spray-json#jsonformats-for-recursive-types

@spydons 解决方案对我不起作用。您也可以通过编写自定义序列化程序来处理递归 类。下面是一个写法的例子:

object Test extends App{

  import spray.json._

  case class Foo(i: Int, foo: Foo)

  implicit object FooJsonFormat extends RootJsonWriter[Foo] {
    override def write(c: Foo)  : JsValue =
      if (c.foo != null) { JsObject("i" -> JsNumber(c.i),"foo" -> write(c.foo)) }
      else { JsObject("i" -> JsNumber(c.i)) }
  }

  println(Foo(20,Foo(10,null)).toJson) //prints {"foo":{"i":10},"i":20}
}