4

How can provide JsonFormats for case class that references itself ?

I'm following this guideline and wrote following code

case class Item(name: String, desc: Option[String], prices: Array[String], subitems: Option[List[Item]])

import spray.json._
import DefaultJsonProtocol._ // !!! IMPORTANT, else `convertTo` and `toJson` won't work

object MyJsonProtocol extends DefaultJsonProtocol {
  implicit val menuItemFormat = jsonFormat(Item, "name", "desc", "prices", "subitems")
}

import MyJsonProtocol._

and I get following error message meaning of which I unfortunately don't understand.

could not find implicit value for evidence parameter of type Hi.MyJsonProtocol.JF[Option[List[mypkg.Item]]]
    implicit val menuItemFormat = jsonFormat(Item, "name", "desc", "prices", "subitems")
                             ^

How can I fix it ?

expert
  • 29,290
  • 30
  • 110
  • 214

1 Answers1

7

for the recursive implicit to find itself, you need to give it an explicit type definition. Change your implicit to:

implicit val menuItemFormat: RootJsonFormat[Item] = jsonFormat(Item.apply, "name", "desc", "prices", "subitems")
stew
  • 11,276
  • 36
  • 49
  • Could you please take a look at this related question ? http://stackoverflow.com/questions/16451042/npe-in-spray-json-because-of-confusing-implicits-context-bound-issue – expert May 08 '13 at 22:10
  • For completion sake https://github.com/spray/spray-json#jsonformats-for-recursive-types – Jaime Agudo Jan 30 '15 at 08:37