您好我在使用spray-json libary whith递归数据结构解析json时有点挣扎。
我有以下案例类结构和协议定义
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.
我错过了重要的事情吗?有人能给我一个暗示吗?
答案 0 :(得分:1)
你必须像你一样用lazyFormat包装你的格式构造函数,但是你还必须提供一个显式的类型注释,如下所示:
implicit val fooFormat: JsonFormat[Foo] = lazyFormat(jsonFormat(Foo, "i", "foo"))
来源:https://github.com/spray/spray-json#jsonformats-for-recursive-types
答案 1 :(得分:0)
@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}
}