Json Play 2.4 中特征的格式化程序
Json formatter for traits in Play 2.4
我有一个特质
trait Role[A, B] {
val _id: Option[A] = None
val value: Option[List[B]] = None
val id: Option[String] = None
}
并且案例 class 扩展了特征
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"。
我在 Whosebug 中尝试了几个可用的示例,在 json 特征格式化程序上没有任何效果。
是的,这是正确的,因为当 Play 尝试为用户进行格式化时,它不知道如何将 Role
格式化为 json.
你可以这样做,首先添加如下内容:
implicit val roleFormat = Json.format[Role]
到object User
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.
我有一个特质
trait Role[A, B] {
val _id: Option[A] = None
val value: Option[List[B]] = None
val id: Option[String] = None
}
并且案例 class 扩展了特征
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"。
我在 Whosebug 中尝试了几个可用的示例,在 json 特征格式化程序上没有任何效果。
是的,这是正确的,因为当 Play 尝试为用户进行格式化时,它不知道如何将 Role
格式化为 json.
你可以这样做,首先添加如下内容:
implicit val roleFormat = Json.format[Role]
到object User
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.