2
votes

Hello I am bit struggling with parsing a json with spray-json libary whith recursive data structure.

I have following case class structure and Protocol defined

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)
}

In the test I am importing:

import spray.json._
import OfferAnalysisReportProtocol._

But I am still getting

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

Am I missing something important here? Could someone give me a hint?

2
Can you try defining variables lazy like implicit lazy val aggsDefFormat and implicit lazy val bucketDefinitionFormat?Mustafa Simav
It does not help to define the variables lazily.spydon

2 Answers

4
votes

You will have to wrap your format constructor with lazyFormat as you have done, but you also have to supply an explicit type annotation like this:

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

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

0
votes

@spydons solution did not work for me. You can handle recursive classes by writing a custom serializer as well. Here's an example for writing:

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}
}