gpt4 book ai didi

scala - 带有对象键的记录的 Circe 通用编解码器推导

转载 作者:行者123 更新时间:2023-12-04 01:21:58 24 4
gpt4 key购买 nike

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

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]

最佳答案

根据 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可用于实现另一种解决方案。

关于scala - 带有对象键的记录的 Circe 通用编解码器推导,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35886060/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com