How to provide JsonFormats for a case class that references itself?

How can I provide JsonFormats for a case class that references itself?

I follow this and wrote the 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 the following error message, which I, unfortunately, do not 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 this?

+4
source share
1 answer

for a recursive implicit, to find yourself, 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") 
+7
source

Source: https://habr.com/ru/post/1479653/


All Articles