10

我有一组从特征继承的案例对象,如下所示:

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

我想将其序列化为 JSON,我只是使用了 Format 机制:

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

但不幸的是,编译器并不高兴,它说:

No unapply or unapplySeq function found

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

4

2 回答 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")
    }
  }
于 2017-01-27T14:57:39.647 回答
5

另一种选择是override def 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会给你案例对象名称

文件: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"}

希望这可以帮助!

于 2018-11-22T18:57:53.290 回答