Play 2.4 中特征的 Json 格式化程序

标签 json playframework traits

我有一个特质

  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/

相关文章:

javascript - Node.js - child_process.exec 和输出重定向

java - Playframework WSRequest POST 登录

generics - 如何从盒装特征对象获取对结构的引用?

json - NSJSONSerialization 解析错误

json - Bash 和 jq - 查找变量中包含的键并更改其值

Ruby on Rails - 如何多次更改变量值并保存?

java - 将 HTML 5 数据属性传递给 Play!表单输入

json - Scala Play Json 读取

oop - Rust 等同于 C++ 的虚函数是什么?

php - 特征中的构造函数定义如何冲突?