Circe通用编解码器派生用于具有对象键的记录

时间:2016-03-09 08:03:35

标签: scala shapeless

我正在尝试实现类似的东西

object Claims {
  import shapeless._
  import shapeless.labelled.FieldType
  import io.circe._
  import io.circe.generic.semiauto._
  import java.util.UUID

  type ClaimOf[V] = FieldOf[V]
  object iss extends ClaimOf[String]
  object subj extends ClaimOf[String]
  object aud extends ClaimOf[Set[String]]
  object client_id extends ClaimOf[UUID]

  implicit val encoder =
    deriveEncoder[FieldType[iss.type, String] :: FieldType[subj.type, String] :: HNil]
}

它不会编译错误 error: could not find implicit value for parameter encode: shapeless.Lazy[io.circe.generic.encoding.DerivedObjectEncoder[shapeless.::[shapeless.labelled.FieldType[Claims.iss.type,String],shapeless.::[shapeless.labelled.FieldType[Claims.subj.type,String],shapeless.HNil]]]] deriveEncoder[FieldType[iss.type, String] :: FieldType[subj.type, String] :: HNil]

1 个答案:

答案 0 :(得分:3)

根据Travis Brown,问题是“泛型推导旨在与Shapeless的通用实例一起使用,并期望FieldType键成为符号。” See discussion on Gitter

我的解决方案:

object Claims {
  import shapeless._
  import shapeless.labelled.FieldType
  import io.circe._
  import io.circe.syntax._
  import io.circe.generic.semiauto._
  import io.circe.generic.encoding.DerivedObjectEncoder
  import java.util.UUID

  abstract case class ClaimOf[V](name: String) extends FieldOf[V]

  object iss extends ClaimOf[String]("iss")
  object subj extends ClaimOf[String]("subj")
  object aud extends ClaimOf[Set[String]]("aud")
  object client_id extends ClaimOf[UUID]("client_id")

  implicit final def encodeClaims[K, H, T <: HList](implicit key: Witness.Aux[K],
                                                       claim: K <:< ClaimOf[H],
                                                       encodeHead: Lazy[Encoder[H]],
                                                       encodeTail: Lazy[DerivedObjectEncoder[T]]
                                                      ): DerivedObjectEncoder[FieldType[K, H] :: T] =
  new DerivedObjectEncoder[FieldType[K, H] :: T] {
    final def encodeObject(a: FieldType[K, H] :: T): JsonObject = a match {
      case h :: t =>
        (key.value.name -> encodeHead.value(h)) +: encodeTail.value.encodeObject(t)
    }
  }

  val encoder = deriveEncoder[FieldType[iss.type, String] :: FieldType[subj.type, String] :: HNil]

  val rec = (iss ->> "issuer") :: (subj ->> "subject") :: HNil

  val json = rec.asJson.spaces2
}

encodeClaims函数基本上是来自circe的原始函数的副本,取代了对键的约束。

This answer可用于实施其他解决方案。