具有递归类定义的 Json 隐式格式

标签 json scala recursion playframework play-json

我定义了一个递归类:

case class SettingsRepository(id: Option[BSONObjectID],
                          name: Option[String],
                          children: Option[List[SettingsRepository]])

JSON 隐式格式如下:

implicit val repositoryFormat = Json.format[SettingsRepository]

如何解决此编译错误? :

No implicit format for Option[List[models.practice.SettingsRepository]] available.
In /path/to/the/file.scala:95

95 implicit val repositoryFormat = Json.format[SettingsRepository] 

我尝试定义一个惰性读/写/格式包装器,但没有成功...... 有人知道一种干净的方法吗?

最佳答案

正如您所发现的,您不能在此处使用 JSON 初始宏,但您可以编写自己的 Format (请注意,我已将 BSONObjectID 替换为为了完整的工作示例):

import play.api.libs.functional.syntax._
import play.api.libs.json._

case class SettingsRepository(
  id: Option[Long],
  name: Option[String],
  children: Option[List[SettingsRepository]]
)

implicit val repositoryFormat: Format[SettingsRepository] = (
  (__ \ 'id).formatNullable[Long] and
  (__ \ 'name).formatNullable[String] and
  (__ \ 'children).lazyFormatNullable(implicitly[Format[List[SettingsRepository]]])
)(SettingsRepository.apply, unlift(SettingsRepository.unapply))

诀窍是提供显式类型注释并隐式使用lazyFormatNullable上的类型参数,而不仅仅是一个类型参数。

关于具有递归类定义的 Json 隐式格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30712175/

相关文章:

scala - 为什么 SBT 的 Scala (2.10) 不包括 Akka?

android - 在 JSON 对象中处理空值

php访问json中的属性

json - 使用一些关键字从 JQ 构建 json 路径

scala - 理解 Scala FP 库

python - 在Python中递归生成n个选择k个组合的列表 - 但返回一个列表

JavaScript : Filter a JSON object from API call to only get the infos I need

mongodb - java.lang.NoSuchFieldException : handle Embedded MongoDB with play framework 异常

c - 这个递归程序如何反转所有字符

python - 现代艺术中的 CP Python 逻辑混淆(Bronze USACO 2017 美国公开赛第 3 页)