自动推导枚举找不到编码器

时间:2019-07-14 20:43:00

标签: scala enums circe

我有一个这样的案例类:

case class Admin(name: String, role: Role)

Role是一个枚举

object Role extends Enumeration {
  type Role = Value
  val Manager = Value
}

当我尝试:

import io.circe.generic.auto._, io.circe.syntax._

val response = Admin("John", Role.Manager).asJson.noSpaces

我收到隐式编码器未找到错误。

not enough arguments for method asJson: (implicit encoder: io.circe.Encoder[Admin])io.circe.Json. Unspecified value parameter encoder.

我认为此错误是由于枚举引起的,所以我更改为:

trait Role

object Role {
  object Manager extends Role
}

但这也行不通。

最后,我尝试过:

trait Role

object Manager extends Role

没有成功。有谁可以帮助我吗?谢谢!

1 个答案:

答案 0 :(得分:1)

enumeratum-circe启用以下语法

object CirceEnumeratumExample extends App {
  import enumeratum._
  import io.circe.generic.auto._, io.circe.syntax._

  sealed trait Role extends EnumEntry
  case object Role extends Enum[Role] with CirceEnum[Role] {
    case object Manager  extends Role
    case object User extends Role
    val values = findValues
  }

  case class Admin(name: String, role: Role)
  val response = Admin("John", Role.Manager).asJson.noSpaces
  println(response)
}

输出

{"name":"John","role":"Manager"}

其中

libraryDependencies += "com.beachape" %% "enumeratum" % "1.5.13",
libraryDependencies += "com.beachape" %% "enumeratum-circe" % "1.5.21"