JsonFormat for case objects inheriting a sealed abstract class

176 views
Skip to first unread message

Josh Lemer

unread,
Oct 23, 2015, 4:57:46 PM10/23/15
to spray.io User List
So I have, for instance

sealed abstract class TemperatureUnit

object TemperatureUnits {
 
case object Celsius extends TemperatureUnit
 
case object Fahrenheit extends TemperatureUnit
}

object TemperatureUnitJsonProtocol extends DefaultJsonProtocol {
 
implicit object TemperatureUnitFormat extends RootJsonFormat[TemperatureUnit] {
   
override def read(json: JsValue) = ???
   
override def write(temperatureUnit: TemperatureUnit) = temperatureUnit match {
     
case TemperatureUnits.Celsius => JsString("Celsius")
     
case TemperatureUnits.FahrenHeit => JsString("Fahrenheit")
   
}
 
}
}

However, when I go and try to use this

TemperatureUnits.Celsius.toJson

I get error:

Error:(15, 22) Cannot find JsonWriter or JsonFormat type class for com.joshlemer.TemperatureUnits.Celsius.type

I also can't seem to be able to explicitly write a CelsiusFormat:

implicit object CelsiusFormat extends RootJsonFormat[TemperatureUnits.Celsius]

doesn't compile, as `TemperatureUnits.Celsius` cannot be found. However I can fix this and probably get what I want if I use 0-parameter case classes, but those are deprecated and so I don't want to use them.

Age Mooij

unread,
Oct 30, 2015, 7:17:58 AM10/30/15
to spray...@googlegroups.com
The type of your format is RootJsonFormat[TemperatureUnit] so it will only be able to read/write instances that are explicitly typed as such. 

So this will work:

val c: TemperatureUnit = Celcius
val f: TemperatureUnit = Fahrenheit

c.toJson
f.toJson

Hope this helps
Age




--
You received this message because you are subscribed to the Google Groups "spray.io User List" group.
To unsubscribe from this group and stop receiving emails from it, send an email to spray-user+...@googlegroups.com.
Visit this group at http://groups.google.com/group/spray-user.
To view this discussion on the web visit https://groups.google.com/d/msgid/spray-user/da4aa46b-7c25-4ac5-9bc5-2cd9d5e2bba6%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages