scala Circe中泛型类的半自动解码

k2arahey  于 2023-04-30  发布在  Scala
关注(0)|答案(2)|浏览(133)

我有以下案例类:

case class QueryResult[T: Decoder](data: T)

它与自动派生一起工作。
但是我不能解决它有一个半自动推导。
下面是我的测试用例:

//import io.circe.generic.auto._ // with this it works
  import io.circe.derivation._

  case class Name(name: String)
  case class QueryResult[T: Decoder](data: T)

  implicit val nameDer = deriveDecoder[Name]
  implicit def result[T: Decoder] = deriveDecoder[QueryResult[T]] // this does not work

这给了我:

Error:(16, 50) No method evidence$1 in pme123.graphql.client.QueryResult[T] (this is probably because a constructor parameter isn't a val)
  implicit def result[T: Decoder] = deriveDecoder[QueryResult[T]]
mrfwxfqh

mrfwxfqh1#

你用的是哪个版本的circe?在0.12.3中,我必须使用import io.circe.generic.semiauto._,下面的代码对我有用:

case class Name(name: String)
case class QueryResult[T: Decoder](data: T)

implicit val nameDer = deriveDecoder[Name]
implicit def result[T: Decoder] = deriveDecoder[QueryResult[T]]

val json = """{"data": {"name": "foo"}}"""
decode[QueryResult[Name]](json)  // Right(QueryResult(Name(foo)))
niknxzdl

niknxzdl2#

遇到了同样的问题。这在关于接受答案的评论中有所解释,但您需要确保在每种类型上添加编码器/解码器。
例如,你遇到了一个问题,不知何故,circe不知道如何解码A,确保你有编码器/解码器一直向下:

case class A(someB: B)
object A {
  implicit val decoder: Decoder[A] = deriveDecoder
}

case class B(something: String)
object B {
  // If you forget this, an implicit decoder cannot be derived for A either
  implicit val decoder: Decoder[B] = deriveDecoder
}

相关问题