我想为值类派生编码器实例。使用该semiauto
机制,我无法派生嵌套类。
想象下面的案例类结构
{
case class Recipient(email: Recipient.Email, name: Recipient.Name)
object Recipient {
case class Email(value: String) extends AnyVal
case class Name(value: String) extends AnyVal
}
}
在菊石外壳中(还添加 Recipient 案例类)
load.ivy("io.circe" %% "circe-core" % "0.6.1")
load.ivy("io.circe" %% "circe-generic" % "0.6.1")
import io.circe._
import io.circe.generic.semiauto._
import io.circe.syntax._
Email
现在为预期的结果派生解码器
Recipient.Email("ab@cd.com").asJson(deriveEncoder[Recipient.Email])
Json = {
"value" : "ab@cd.com"
}
派生一个Encoder[Recipient]
不起作用
deriveDecoder[Recipient]
could not find Lazy implicit value of type
io.circe.generic.decoding.DerivedDecoder[$sess.cmd5.Recipient]
我想做的是派生一个Encoder[Recipient.Email]
返回包装类型的。如果我明确派生编解码器,这个小片段就可以工作。
import shapeless.Unwrapped
implicit def encodeAnyVal[W <: AnyVal, U](
implicit unwrapped: Unwrapped.Aux[W, U],
encoderUnwrapped: Encoder[U]): Encoder[W] = {
Encoder.instance[W](v => encoderUnwrapped(unwrapped.unwrap(v)))
}
Recipient.Email("ab@cd.com").asJson(encodeAnyVal[Recipient.Email, String])
res11: Json = "ab@cd.com"
我仍然无法得出一个Encoder[Recipient]
implicit val emailEncoder: Encoder[Recipient.Email] = encodeAnyVal[Recipient.Email, String]
implicit val nameEncoder: Encoder[Recipient.Name] = encodeAnyVal[Recipient.Name, String]
deriveDecoder[Recipient]
cmd14.sc:1: could not find Lazy implicit value of type io.circe.generic.decoding.DerivedDecoder[$sess.cmd5.Recipient]
有没有人做过类似的事情?
在此先感谢,穆基