序列化案例对象扩展特性

Kev*_*ith 2 serialization scala playframework-2.0

给定trait Conjunctionwith ANDORcase对象子类型:

  trait Conjunction
  case object AND extends Conjunction
  case object OR extends Conjunction
Run Code Online (Sandbox Code Playgroud)

使用Play 2 JSON,我尝试编写以下内容Writes[Conjunction]

  implicit object ConjunctionWrites extends Writes[Conjunction] {
    implicit val orWrites: Writes[OR] = Json.writes[OR]
    implicit val andWrites: Writes[AND] = Json.writes[AND]

    def writes(c: Conjunction) = c match {
      case a@AND => Json.toJson(a)(andWrites)
      case o@OR => Json.toJson(o)(orWrites)
    }
  }
Run Code Online (Sandbox Code Playgroud)

但是我有很多 not found: type AND/OR错误。

如何序列化这些case object

win*_*ner 5

创建案例对象时,将使用该名称而不是类型创建一个值。因此,AND并且OR不作为类型存在。如果你想引用一个对象的情况下,使用的类型.type,如AND.type

但是,该Json.writes宏仅适用于案例类,不适用于案例对象。您必须编写自己的定义:

implicit object ConjunctionWrites extends Writes[Conjunction] {
  def writes(c: Conjunction) = c match {
    case AND => Json.toJson("AND")
    case OR => Json.toJson("OR")
  }
}
Run Code Online (Sandbox Code Playgroud)