我正在尝试实现类似
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可用于实现另一个解决方案。