使用 Circe 解码 Normal Class(不是 case class)

Use Circe to decode Normal Class (not case class)

我写了这段代码来使用 circe 读写 josn

import io.circe._, io.circe.generic.auto._, io.circe.parser._, io.circe.syntax._
case class Foo(i: Int)
val f = Foo(10)
val json = f.asJson.toString
val t1 = decode[Foo](json)

这很管用。但是如果我创建一个正常的 class Bar

class Bar { var i : Int = 0 }
decode[Bar](json)

现在我得到错误

 could not find implicit value for evidence parameter of type io.circe.Decoder[$sess.cmd25.Bar]

那么是否可以使用正常的 classes 并使用 Circe 从 json 解码它们?

使用 io.circe.generic.auto._,您正在使用 Circe 的自动泛型派生,它由 Shapeless 的 LabelledGeneric 类型class 支持。 LabelledGeneric 仅适用于产品类型,例如元组和大小写 classes。这就是您看到此错误的原因,因为 Circe 的自动模式无法为您的普通 class 自动派生解码器实例。您可以做的是手动 implement 为您的 class 解码器(参见自定义 encoders/decoders 部分)。