如何在Play Json Writes中包含案例类正文成员?

时间:2016-11-02 11:50:46

标签: scala play-json

我有:

sealed trait MessageType { def description: String }
object MessageType {
  case object Important extends MessageType { override val description = "important" }
  case object Normal extends MessageType { override val description = "normal" }
}

trait Message { def messageType: MessageType }

case class SomeMessage(from: String, to: String, text: String) extends Message {
  override val messageType: MessageType = MessageType.Important
}

object SomeMessage {
  implicit val someMessageWrites: Writes[SomeMessage] = (
    (JsPath \ "from").write[String] and
    (JsPath \ "to").write[String] and
    (JsPath \ "text").write[String]
  )(unlift(SomeMessage.unapply))
}

然后使用Json.toJason(someMessage)会生成带有fromtotext字段的Json,但我还希望有一个字段messageType价值"重要的"。

我可以将消息类型字段包含为构造函数参数,但这似乎是一个黑客 - 消息类型字段应该是固定的,而不是指定。

有可能实现这一目标吗?

0 个答案:

没有答案
相关问题