My spray json serialization does not seem to work, as my tests just keeps running, when i am trying to serialize an Either[TimeSlot, DateSlot] object to JsValue, and vice-versa when i am trying to parse a json string and convert it to Either[TimeSlot,DateSlot] object.
I have been reading some others with same issues, just with a Seq[Either[int,String], but the solution was hardly understood. Furthermore i have tried using the standardized Either json format, but problem is, that i need to define it with names and types, to make it more intuitive.
TimeSlot and DateSlot, is working fine.
implicit object eitherDateOrTimeSlotFormat
extends RootJsonFormat[Either[TimeSlot, DateSlot]] {
private val timeSlotTypeKey = "timeSlotType"
private val timeSlotValueKey = "timeSlotValue"
override def write(obj: Either[TimeSlot, DateSlot]): JsValue = obj match {
case Left(timeSlot) ⇒
JsObject(
timeSlotTypeKey → JsString("timeSlot"),
timeSlotValueKey → timeSlot.toJson
)
case Right(dateSlot) =>
JsObject(
timeSlotTypeKey → JsString("dateSlot"),
timeSlotValueKey → dateSlot.toJson
)
}
override def read(json: JsValue): Either[TimeSlot, DateSlot] = json match {
case JsObject(fields)
if fields.isDefinedAt("timeSlotType") && fields
.isDefinedAt("timeSlotValue") ⇒
fields("timeSlotType") match {
case JsString(slotType) ⇒
slotType match {
case "timeSlot" ⇒
Left(fields("timeSlotValue").convertTo[TimeSlot])
case "dateSlot" ⇒
Right(fields("timeSlotValue").convertTo[DateSlot])
case _ ⇒
throw DeserializationException(
s"${json.compactPrint} did not match protocol"
)
}
case _ ⇒
throw DeserializationException(
s"${json.compactPrint} did not match protocol"
)
}
}
} It seems the tests is running forever, like if they were stuck in some kind of infinity-loop, and would of course be expected to just serialize, so my tests would assert the results.