user3139545 user3139545 - 3 months ago 14
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)
CustomColor(VColor)


Now I want this to produce a JSON like so:

{c:"v_color"}

Answer

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)
}

Then

alex-alex@ import MyJsonProtocol._
alex-alex@ CustomColor(VColor).toJson
res18: JsValue = {"c":"v_color"}
Comments