Circe和Scala的枚举类型 [英] Circe and Scala's Enumeration type
问题描述
我想把头围在Circe上.
I'm trying to wrap my head around Circe.
所以,这是我得到的模型:
So, here's the model I've been given:
object Gender extends Enumeration {
type Gender = Value
val Male, Female, Unisex, Unknown = Value
}
case class Product(id: String, gender: Gender.Value)
我想
a)将此简单示例编码为JSON字符串
a) encode this simple example to a JSON string
val product = Product(id = "1234", gender = Gender.Female)
b)将生成的JSON映射回Product案例类.
b) map the resulting JSON back onto the Product case class.
我自己的尝试并没有使我走得很远:
My own attempt didn't get me very far:
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
^
我不知道为什么会抛出该异常以及解决方案的外观.也许是Enumeration类型的用法?但是,我只是在猜测.
I've no idea why this exception is thrown and what the solution could look like. Maybe it's the usage of the Enumeration type? But, I'm only guessing.
推荐答案
尝试使用以下方法为枚举定义自己的编码器和解码器:
Try defining your own encoders and decoders for the enum using:
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的标准部分,但您可能需要为自己的枚举创建一个编码器/解码器.
These are needed because the automatic/semiautomatic derivers only work for hierarchies of sealed trait
s and case classes
as far as I know. The reason you see that error is because the derived codecs for Product
will implicitly require encoders/decoders for the types of each of it's parameters. An encoder/decoder for String
is a standard part of Circe, but you'll probably need to create ones for your own enumerations.
这篇关于Circe和Scala的枚举类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!