【问题标题】:How can provide JsonFormats for case class that references itself?如何为引用自身的案例类提供 JsonFormats?
【发布时间】: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")
                             ^

我该如何解决?

【问题讨论】:

    标签: json scala spray-json


    【解决方案1】:

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

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

    【讨论】:

    猜你喜欢
    • 2013-05-15
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    • 2012-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-05
    相关资源
    最近更新 更多