user3139545 user3139545 - 1 year ago 112
JSON Question

trait with only case objects custom implementation in spray json

Given I have the following declaration:

sealed trait Color
case object DColor extends Color
case object CColor extends Color
case object VColor extends Color

And then I use them In a case class like so:

case class CustomColor(c: Color)

Now I want this to produce a JSON like so:


Answer Source

Should define a custom format:

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"}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download