gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 08:14:20 24 4
gpt4 key购买 nike

我已经编写了这段代码来使用 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 中解码它们?

最佳答案

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

关于scala - 使用 Circe 解码 Normal Class(不是 case class),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43374285/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com