使用 Json.format 没有可用的 MyClass 隐式格式

No implicit format for MyClass available using Json.format

在 Json.format 上使用复杂对象作为另一个对象的属性时出现错误。

我有两个 类:RoleDTOEmailInvitationDTOEmailInvitationDTO 有一个 RoleDTO。所以,我宣布:

case class RoleDTO(id:Option[Long] = None, roleType:Int, userID:Long, fromHousingUnitID:Option[Long] = None, isAdmin:Option[Boolean] = None, fromResidentUserID:Option[Long] = None, documentNumber:Option[String] = None, fromCondoID:Option[Long] = None)
object RoleDTO { val roleFormat = Json.format[RoleDTO] }

case class EmailInvitationDTO(firstName:String, lastName:String, email:String, role:RoleDTO)
object EmailInvitationDTO{ val emailInvitationFormat = Json.format[EmailInvitationDTO] }

我收到错误消息:RoleDTO 没有可用的隐式格式。即使我在 emailInvitationFormat[=30 之前的一行中声明了 roleFormat 变量=]:

object EmailInvitationDTO {
    val roleFormat = Json.format[RoleDTO]
    val emailInvitationFormat = Json.format[EmailInvitationDTO]
}

有人知道缺少什么吗?谢谢

您需要在 EmailInvitationDTO 对象声明中包含一个隐含的 roleFormatJson.format 宏在编译时寻找隐式的 Json 格式,否则它不知道如何 read/write 你的 EmailInvitationDTO.[=17 中的 RoleDTO =]

因此,在创建 emailInvitationFormat 之前,您需要在范围内添加以下行:

implicit val roleFormat = Json.format[RoleDTO]