Play Framework JSON 案例对象的格式

Play Framework JSON Format for Case Objects

我有一组案例对象继承自如下特征:

  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

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

好的,我知道必须做什么了!

这里是:

  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")
    }
  }

另一种选择是 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"}

希望对您有所帮助!