使用Json.format时,MyClass没有隐式格式

adh*_*eus 5 json scala implicit playframework-2.0

我在使用复杂对象作为Json.format上另一个对象的属性时遇到错误.

我有两个类:RoleDTOEmailInvitationDTO.EmailInvitationDTO有一个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] }
Run Code Online (Sandbox Code Playgroud)

我收到错误:没有可用的RoleDTO隐式格式.即使我宣布roleFormat中前行变量emailInvitationFormat:

object EmailInvitationDTO {
    val roleFormat = Json.format[RoleDTO]
    val emailInvitationFormat = Json.format[EmailInvitationDTO]
}
Run Code Online (Sandbox Code Playgroud)

谁知道缺少什么?谢谢.

jos*_*ley 5

您需要roleFormatEmailInvitationDTO对象声明中包含隐式.该Json.format宏查找隐含的Json格式在编译的时候,否则会不知道如何读/写RoleDTO在你的EmailInvitationDTO.

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

implicit val roleFormat = Json.format[RoleDTO]
Run Code Online (Sandbox Code Playgroud)

  • 在尝试解决不同的问题时找到了这个,但帖子给了我一些我的代码有什么问题的提示,所以如果有其他人遇到与我相同的问题,那么值得指出的是需要在正确的顺序,所以RoleDto需要在EmailInvocationDto之前. (2认同)