另一种选择是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"}
希望这可以帮助!