我有:
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)
会生成带有from
,to
和text
字段的Json,但我还希望有一个字段messageType
价值"重要的"。
我可以将消息类型字段包含为构造函数参数,但这似乎是一个黑客 - 消息类型字段应该是固定的,而不是指定。
有可能实现这一目标吗?