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

Xan*_*Xan 6 recursion json scala playframework play-json

我有一个定义的递归类:

case class SettingsRepository(id: Option[BSONObjectID],
                          name: Option[String],
                          children: Option[List[SettingsRepository]])
Run Code Online (Sandbox Code Playgroud)

使用JSON隐式格式如下:

implicit val repositoryFormat = Json.format[SettingsRepository]
Run Code Online (Sandbox Code Playgroud)

如何解决此编译错误?:

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

95 implicit val repositoryFormat = Json.format[SettingsRepository] 
Run Code Online (Sandbox Code Playgroud)

我试图定义一个懒惰的读/写/格式包装器没有任何成功......任何人都知道一个干净的方法来做到这一点?

任何帮助将不胜感激;

先感谢您.

Tra*_*own 8

正如你已经发现,你不能在这里使用JSON以来宏,但你可以编写自己的Format(请注意,我换成BSONObjectIDLong一个完整的工作示例的缘故):

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))
Run Code Online (Sandbox Code Playgroud)

诀窍是提供显式类型注释并使用implicitly而不仅仅是类型参数lazyFormatNullable.