具有 Circe 实现的通用 json 解码器特征
Generic json decoder trait with Circe implementation
我有一个特征用于注入 json 解码器作为对我项目组件的依赖:
trait JsonDecoder {
def apply[T](s: String): Option[T]
}
当我尝试用 Circe 实现它时:
import io.circe.generic.auto._
import io.circe.parser.decode
case class CirceJsonDecoder() extends JsonDecoder {
def apply[T](s: String): Option[T] = {
decode[T](s).fold(_ => None, s => Some(s))
}
}
和运行:
case class C()
def test(d: JsonDecoder) = d[C]("{}")
test(CirceJsonDecoder())
它没有编译错误:
could not find implicit value for parameter decoder: io.circe.Decoder[T]
我尝试为 T
添加 ClassTag
、TypeTag
或 WeakTypeTag
上下文边界,但它仍然找不到 Decoder
的隐式值。
我无法将 Decoder
上下文绑定或隐式参数添加到 JsonDecoder.apply
,因为使用它的组件不应该知道实现细节。
我应该如何提供隐式 io.circe.Decoder
?可能有某种方法可以从 TypeTag
?
获取它
我不认为你可以在不影响你的 apply 方法签名的情况下以任何方式涉及 circe。
如果可以,则意味着 circe.auto_
能够在任何类型 T 的范围内引入隐式解码器,这是不正确的。
AFAIK,没有比在你的函数中添加隐式 Decoder
来表明它实际上知道如何处理这种类型更好的类型注释了(如果你愿意,你可以使用 T: Decoder
版本,但最终是一样的)。
我有一个特征用于注入 json 解码器作为对我项目组件的依赖:
trait JsonDecoder {
def apply[T](s: String): Option[T]
}
当我尝试用 Circe 实现它时:
import io.circe.generic.auto._
import io.circe.parser.decode
case class CirceJsonDecoder() extends JsonDecoder {
def apply[T](s: String): Option[T] = {
decode[T](s).fold(_ => None, s => Some(s))
}
}
和运行:
case class C()
def test(d: JsonDecoder) = d[C]("{}")
test(CirceJsonDecoder())
它没有编译错误:
could not find implicit value for parameter decoder: io.circe.Decoder[T]
我尝试为 T
添加 ClassTag
、TypeTag
或 WeakTypeTag
上下文边界,但它仍然找不到 Decoder
的隐式值。
我无法将 Decoder
上下文绑定或隐式参数添加到 JsonDecoder.apply
,因为使用它的组件不应该知道实现细节。
我应该如何提供隐式 io.circe.Decoder
?可能有某种方法可以从 TypeTag
?
我不认为你可以在不影响你的 apply 方法签名的情况下以任何方式涉及 circe。
如果可以,则意味着 circe.auto_
能够在任何类型 T 的范围内引入隐式解码器,这是不正确的。
AFAIK,没有比在你的函数中添加隐式 Decoder
来表明它实际上知道如何处理这种类型更好的类型注释了(如果你愿意,你可以使用 T: Decoder
版本,但最终是一样的)。