Play框架中的Case Objects的JSON格式

10

我有一组继承自下面特质的案例对象:

  sealed trait UserRole
  case object SuperAdmin extends UserRole
  case object Admin extends UserRole
  case object User extends UserRole

我想将这个对象序列化为JSON,并且我刚刚使用了格式化机制:

implicit val userRoleFormat: Format[UserRole] = Json.format[UserRole]

但不幸的是,编译器并不满意,它说:

No unapply or unapplySeq function found

我的案例对象有什么问题?

2个回答

11

好的,我明白了必须要做什么!

这就是:

  implicit object UserRoleWrites extends Writes[UserRole] {
    def writes(role: UserRole) = role match {
      case Admin => Json.toJson("Admin")
      case SuperAdmin => Json.toJson("SuperAdmin")
      case User => Json.toJson("User")
    }
  }

1
重点不在于案例对象,而在于密封特质/族,该特性目前在最新版本中不被宏支持,但将在下一个版本中加入:https://github.com/playframework/play-json/pull/16 - cchantep
2
该拉取请求解决了案例类的问题,但对于案例对象则没有。 - gcaliari

5
另一种选择是像这样覆盖toString

文件:Status.scala

    package models

    trait Status
    case object Active extends Status {
      override def toString: String = this.productPrefix
    }
    case object InActive extends Status {
      override def toString: String = this.productPrefix
    }

this.productPrefix 将会给你返回 case 对象的名称。

文件:Answer.scala

package models

import play.api.libs.json._

case class Answer(
    id: Int,
    label: String,
    status: Status
) {
  implicit val answerWrites = new Writes[Answer] {
    def writes(answer: Answer): JsObject = Json.obj(
      "id" -> answer.id,
      "label" -> answer.label,
      "status" -> answer.status.toString
    )
  }
  def toJson = {
    Json.toJson(this)
  }
}

文件:Controller.scala

import models._
val jsonAnswer = Answer(1, "Blue", Active).toJson
println(jsonAnswer)

你需要:

{"id":1,"label":"Blue","status":"Active"}

希望这能帮到你!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接