Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can provide JsonFormats for case class that references itself?

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 ?

like image 761
expert Avatar asked Mar 25 '23 01:03

expert


1 Answers

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")
like image 140
stew Avatar answered Apr 12 '23 15:04

stew