使用Circe解码普通类(不是案例类)

Kno*_*uch 1 scala circe

我已经编写了这段代码来使用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)
Run Code Online (Sandbox Code Playgroud)

这非常有效.但是,如果我创建一个普通的类Bar

class Bar { var i : Int = 0 }
decode[Bar](json)
Run Code Online (Sandbox Code Playgroud)

现在我收到错误

 could not find implicit value for evidence parameter of type io.circe.Decoder[$sess.cmd25.Bar]
Run Code Online (Sandbox Code Playgroud)

那么有可能使用普通类并使用Circe从json解码它们吗?

LMe*_*yer 5

有了io.circe.generic.auto._,你正在使用Circe的自动泛型推导,它由Shapeless的LabelledGeneric类型类支持.LabelledGeneric仅适用于元组和案例类等产品类型.这就是你看到这个错误的原因,因为Circe的自动模式无法为你的普通类自动派生一个Decoder实例.您可以做的是为您的类手动实现解码器(请参阅自定义编码器/解码器部分).