具有Circe实现的通用json解码器特性

时间:2016-12-09 11:03:02

标签: scala circe

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

CREATE TABLE hotel(
id_Hotel
...

)

CREATE TABLE Manager(
ID_Manager
...

)

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

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

并运行:

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] 添加ClassTagTypeTagWeakTypeTag上下文边界,但仍无法找到T的隐含值。

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

我应该如何提供隐式JsonDecoder.apply?可能有一些方法可以从io.circe.Decoder获得它吗?

1 个答案:

答案 0 :(得分:4)

我认为你不能以任何方式影响你的申请方法签名。 如果可以的话,它意味着circe.auto_能够为任何类型T的范围带来隐式解码器,这是不正确的。

AFAIK,没有比向你的函数添加隐式Decoder更好的类型注释来表示它实际上知道如何处理这种类型(如果你愿意,你可以使用{{1版本,但它最终是相同的。)

相关问题