具有 Circe 实现的通用 json 解码器特征 [英] Generic json decoder trait with Circe implementation

查看:41
本文介绍了具有 Circe 实现的通用 json 解码器特征的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个特征用于将 json 解码器作为对我项目组件的依赖项注入:

I have a trait used to inject json decoder as dependency to components of my project:

trait JsonDecoder {
  def apply[T](s: String): Option[T]
}

当我尝试使用 Circe 实现它时:

When I try to implement it with 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 添加 ClassTagTypeTagWeakTypeTag 上下文边界,但仍然找不到Decoder 的隐含值.

I tried to add ClassTag, TypeTag or WeakTypeTag context bounds for T but it still can not find implicit value for Decoder.

我不能将 Decoder 上下文绑定或隐式参数添加到 JsonDecoder.apply 因为使用它的组件不应该知道实现细节.

I can not add Decoder context bound or implicit parameter to JsonDecoder.apply because components what use it should not know about implementation details.

我应该如何提供隐式io.circe.Decoder?可能有什么方法可以从 TypeTag 获取它?

How should I provide implicit io.circe.Decoder? May be there is some way to get it from TypeTag?

推荐答案

我认为你不能不以任何涉及 circe 的方式影响你的 apply 方法签名.如果可以,那就意味着 circe.auto_ 能够为任何类型 T 引入隐式解码器,但事实并非如此.

I don't think you can without affecting your apply method signature in any way involving circe. If you could, it'd mean circe.auto_ is capable of bringing an implicit decoder in scope for any type T, which is not true.

AFAIK,没有比向函数添加隐式 Decoder 更好的类型注释了,以向 circe 发出信号,表明它实际上知道如何处理这种类型(如果您愿意,可以使用 T:Decoder 版本,但最后还是一样).

AFAIK, there's no better type annotation than adding an implicit Decoder to your function to signal circe that it actually knows how to handle this type (if you prefer, you can use the T: Decoder version, but it's the same in the end).

这篇关于具有 Circe 实现的通用 json 解码器特征的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆