鉴于我有以下声明:
sealed trait Color
case object DColor extends Color
case object CColor extends Color
case object VColor extends Color
然后我在类似的案例类中使用它们:
case class CustomColor(c: Color)
CustomColor(VColor)
现在我希望这样生成一个像这样的JSON:
{c:"v_color"}
答案 0 :(得分:3)
应定义自定义格式:
object MyJsonProtocol extends DefaultJsonProtocol {
implicit object ColorJsonFormat extends RootJsonFormat[Color] {
def write(c: Color) = c match {
case VColor => JsString("v_color")
case _ => JsString("foo")
}
def read(value: JsValue) = ???
}
implicit val customColorFormat = jsonFormat1(CustomColor.apply)
}
然后
alex-alex@ import MyJsonProtocol._
alex-alex@ CustomColor(VColor).toJson
res18: JsValue = {"c":"v_color"}