【发布时间】:2019-11-19 13:25:14
【问题描述】:
我的问题涉及 mixel 提供的第二种解决方案:Scala Circe with generics
请注意,Circe 中名为 Auto 的特征在当前版本的 Circe 中已重命名为 AutoDerivation。
我正在使用 mixel 在他的 StackOverflow 解决方案中提供的解决方案,但无法使其正常工作。我已经尝试过将我的 Circe 版本更新到最新版本并确保已导入 Macro Paradise 插件,但仍然没有运气。
这是我的代码。第一个是它自己的文件,称为 CirceGeneric。
import io.circe._
import io.circe.parser._
import io.circe.generic.extras._
object CirceGeneric {
trait JsonEncoder[T] {
def apply(in: T): Json
}
trait JsonDecoder[T] {
def apply(s: String): Either[Error, T]
}
object CirceEncoderProvider {
def apply[T: Encoder]: JsonEncoder[T] = new JsonEncoder[T] {
def apply(in: T) = Encoder[T].apply(in)
}
}
object CirceDecoderProvider {
def apply[T: Decoder]: JsonDecoder[T] = new JsonDecoder[T] {
def apply(s: String) = decode[T](s)
}
}
}
object Generic extends AutoDerivation {
import CirceGeneric._
implicit def encoder[T: Encoder]: JsonEncoder[T] = CirceEncoderProvider[T]
implicit def decoder[T: Decoder]: JsonDecoder[T] = CirceDecoderProvider[T]
}
第二种是使用 Akka 函数 responseAs 的单元测试方法。该方法出现在名为 BaseServiceTest 的类中。
def responseTo[T]: T = {
def response(s: String)(implicit d: JsonDecoder[T]) = {
d.apply(responseAs[String]) match {
case Right(value) => value
case Left(error) => throw new IllegalArgumentException(error.fillInStackTrace)
}
}
response(responseAs[String])
}
想法是将responseAs[String]的结果(返回一个字符串)转换成解码的case类。
代码未按预期运行。 Intellij 没有检测到任何缺失的隐式,但是当编译时间到来时,我遇到了问题。我应该提到 BaseServiceTest 文件包含 CirceGeneric._ 和 Generic._ 的导入,因此缺少导入语句不是问题。
[错误] [...]/BaseServiceTest.scala:59:找不到参数 d 的隐式值:[...]CirceGeneric.JsonDecoder[T] [错误] 响应(responseAs[String])
从 Decoder[T] 到 JsonDecoder[T] 的隐式转换没有发生,或者 Decoder[T] 实例没有被创建。无论哪种方式,都有问题。
【问题讨论】: