我正在尝试使用无形从任意案例类中读取 json。
目前我正在尝试执行以下步骤
从 T,我有一个 FieldType[K1, V1] :: FieldType[K2, V2] :: ... 使用 LabelledGeneric
然后我想构建一个 Reads[V1] :: Reads[V2] 类型的 HList ...
这是我正在使用的代码:
/*
* To build the json reads from T
*/
trait HReads[PRepr <: HList] {
type Out
def reads: Out
}
object HReads {
type Aux[PRepr <: HList, Out1 <: HList] = HReads[PRepr] { type Out = Out1 }
implicit def readsHNil(): Aux[HNil, HNil] = new HReads[HNil] {
type Out = HNil
override def reads: Out = {
throw new RuntimeException("Oups")
}
}
implicit def readsSingleton[T, K <: Symbol](
implicit
kWitness: Witness.Aux[K],
jsReads: play.api.libs.json.Reads[T]
): Aux[FieldType[K, T] :: HNil, Reads[T] :: HNil] = new HReads[FieldType[K, T] :: HNil] {
type Out = Reads[T] :: HNil
override def reads: Out = {
val name: String = kWitness.value.name
val pathReads: Reads[T] = (__ \ name).read[T](jsReads)
pathReads :: HNil
}
}
implicit def readsStd[T, K <: Symbol, RestRepr <: HList, Rest <: HList](
implicit
kWitness: Witness.Aux[K],
jsReads: Reads[T],
hreads: Lazy[HReads.Aux[RestRepr, Rest]]
): Aux[FieldType[K, T] :: RestRepr, Reads[T] :: Rest] = new HReads[FieldType[K, T] :: RestRepr] {
type Out = Reads[T] :: Rest
override def reads: Out = {
val name: String = kWitness.value.name
val pathReads: Reads[T] = (__ \ name).read[T](jsReads)
val value: Rest = hreads.value.reads
pathReads :: value
}
}
def jsonReads[P]: JsonReads[P] = new JsonReads[P] {}
implicit class JsonReadsOps[In](in: JsonReads[In]) {
def jsonReads[K <: Symbol, T, InRepr <: HList, HR <: HList]()(
implicit
gen: LabelledGeneric.Aux[In, FieldType[K, T] :: InRepr],
hreads: HReads.Aux[FieldType[K, T] :: InRepr, Reads[T] :: HR]
): Reads[T] :: HR = {
hreads.reads
}
}
}
// And trying to use this like that :
import HReads._
implicit val l = LabelledGeneric[MonPojo]
private val allReads = jsonReads[MonPojo].jsonReads()
println(s"All Reads $allReads")
//[error] validation\validation.scala:428: could not find implicit value for parameter hreads: validation.validations.HReads.Aux[shapeless.labelled.FieldType[K,T] :: InRepr,play.api.libs.json.Reads[T] :: HR]
//[error] private val allReads = jsonReads[MonPojo].jsonReads()
//[error] ^
//[error] one error found
有人可以帮助我吗?
谢谢亚历克斯。