【问题标题】:Use Circe to decode Normal Class (not case class)使用 Circe 解码普通类(不是案例类)
【发布时间】:2017-04-13 03:00:10
【问题描述】:

我已经编写了这段代码来使用 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)

这很好用。但是如果我创建一个普通的类 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]

那么是否可以使用普通类并使用 Circe 从 json 解码它们?

【问题讨论】:

  • 是的,它只是不能为你自动生成解码器,所以你必须自己编写。

标签: scala circe


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2019-03-15
    • 2020-05-16
    • 2019-03-13
    • 2019-06-05
    • 1970-01-01
    • 2018-05-03
    • 2018-10-22
    • 2018-10-31
    • 2017-01-11
    相关资源
    最近更新 更多