用于案例对象的Play Framework JSON格式

时间:2017-01-27 14:54:48

标签: scala playframework play-json

我有一组案例对象,它们继承自下面的特征:

  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 个答案:

答案 0 :(得分:5)

好的,我想出了必须做的事情!

这是:

  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 :(得分:4)

另一个选择是像这样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"}

希望这会有所帮助!