json - Circe 和 Scala 的枚举类型

标签 json scala circe

我正试图将我的头环绕在 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/

相关文章:

scala - 如何在 ByteString 中获取迭代器的当前位置?

scala - 如何测试一个集合是否至少包含另一个集合中的一个值

scala - 如何将解析器与不同类型的 Elem 结合使用

json - 使用自定义表示在 Scala 中对 ADT 进行通用派生

json - Scala Circe。编码器类型 任意

javascript - 将无序列表转换为 JSON

javascript - js如何在使用文件:///protocol时动态加载json文件

json - 将 firebase 生成的 json 数据集导入 mongodb

scala - 如何在 Circe 的 Scala 中使用泛型?

c# - 如何使用 Json.NET 将 IHtmlString 序列化为 JSON?