如何为引用自身的案例类提供 JsonFormats?

Posted

技术标签:

【中文标题】如何为引用自身的案例类提供 JsonFormats?【英文标题】:How can provide JsonFormats for case class that references itself? 【发布时间】:2013-05-02 03:28:07 【问题描述】:

如何为引用自身的案例类提供JsonFormats?

我遵循 this 指南并编写了以下代码

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._

我收到以下错误消息的含义,很遗憾我不明白。

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")
                             ^

我该如何解决?

【问题讨论】:

【参考方案1】:

要让递归隐式找到它自己,你需要给它一个显式的类型定义。将您的隐式更改为:

implicit val menuItemFormat: RootJsonFormat[Item] = jsonFormat(Item.apply, "name", "desc", "prices", "subitems")

【讨论】:

你能看看这个相关的问题吗? ***.com/questions/16451042/… 为了完整起见github.com/spray/spray-json#jsonformats-for-recursive-types

以上是关于如何为引用自身的案例类提供 JsonFormats?的主要内容,如果未能解决你的问题,请参考以下文章