繁体   English   中英

Either [TimeSlot,DateSlot]的自定义Spray json格式陷入某种类型推断循环中

[英]Custom spray json format of Either[TimeSlot,DateSlot] stuck in some kind of type-inference loop

我喷JSON序列化似乎并没有工作,因为我的测试中只是不断运行,当我试图序列非彼[时隙,DateSlot]对象JsValue,反之亦然,当我试图解析JSON字符串,并将其转换到[TimeSlot,DateSlot]对象。

我一直在阅读其他一些具有相同问题的东西,只是使用Seq [Either [int,String],但是解决方案却很难理解。 此外,我尝试使用标准化的Either json格式,但是问题是,我需要使用名称和类型对其进行定义,以使其更加直观。

TimeSlot和DateSlot工作正常。

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

}测试似乎永远在运行,就像它们陷入某种无限循环一样,当然应该期望它们只是序列化,所以我的测试会断言结果。

这不是程序错误,似乎Idea Intellij社区,Sbt测试或scalac有问题。 但是我手动测试了代码,而不是在测试环境中运行,一切都很好。

我以为是无限循环测试

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM