我正试图将我的头环绕在 Circe 上。
所以,这是我得到的模型:
object Gender extends Enumeration {
type Gender = Value
val Male, Female, Unisex, Unknown = Value
}
case class Product(id: String, gender: Gender.Value)
我想要
a) 将此简单示例编码为 JSON 字符串
val product = Product(id = "1234", gender = Gender.Female)
b) 将生成的 JSON 映射回 Product 案例类。
我自己的尝试并没有让我走得很远:
object JsonProtocol {
implicit val productDecoder: Decoder[Product] = deriveDecoder
implicit val productEncoder: Encoder[Product] = deriveEncoder
}
导致编译时错误
Error:(52, 49) could not find Lazy implicit value of type io.circe.generic.decoding.DerivedDecoder[A]
implicit val productDecoder: Decoder[Product] = deriveDecoder
^
我不知道为什么会抛出这个异常以及解决方案会是什么样子。也许是枚举类型的用法?但是,我只是猜测。
最佳答案
尝试使用以下方法为枚举定义自己的编码器和解码器:
Decoder.enumDecoder[E <: Enumeration](enum: E)
Encoder.enumEncoder[E <: Enumeration](enum: E)
就像是:
object JsonProtocol {
implicit val genderDecoder: Decoder[Gender.Value] = Decoder.enumDecoder(Gender)
implicit val genderEncoder: Encoder[Gender.Value] = Encoder.enumEncoder(Gender)
implicit val productDecoder: Decoder[Product] = deriveDecoder
implicit val productEncoder: Encoder[Product] = deriveEncoder
}
这些是必需的,因为自动/半自动派生器仅适用于
sealed trait
的层次结构。 s 和 case classes
据我所知。您看到该错误的原因是 Product
的派生编解码器将隐含地要求编码器/解码器用于每个参数的类型。 String
的编码器/解码器是 Circe 的标准部分,但您可能需要为自己的枚举创建一个。
关于json - Circe 和 Scala 的枚举类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42068680/