我有一个特质
trait Role[A, B] {
val _id: Option[A] = None
val value: Option[List[B]] = None
val id: Option[String] = None
}
以及扩展特征的案例类
case class User (value1: Option[Role] = None, value2: Option[String] = None) extends Role
object User {
implicit val jsonFormatter: Format[User] = Json.format[User]
}
并且由于错误“No Json formattor for Role”而无法编译。
我尝试了 stackoverflow 中提供的几个示例,在特征的 json 格式化程序上没有任何效果。
最佳答案
是的,这是正确的,因为当 Play 尝试对 User 进行格式化时,它不知道如何将 Role
格式化为 json。
您可以通过首先添加以下内容来做到这一点:
implicit val roleFormat = Json.format[Role]
到对象用户
Play 文档的要求:
These macros rely on a few assumptions about the type they’re working with :
- It must have a companion object having apply and unapply methods
- The return types of the unapply must match the argument types of the apply method.
- The parameter names of the apply method must be the same as the property names desired in the JSON.
Case classes natively meet these requirements. For more custom classes or traits, you might have to implement them.
关于Play 2.4 中特征的 Json 格式化程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42085529/