我正在尝试对案例类使用精炼类型,但无法弄清楚编码器实际上如何工作。对于 json 解析,circe 与 https4s 库一起使用。
type AgeT = Int Refined Interval.ClosedOpen[0,100]
type NameT = String Refined NonEmptyString
case class Person(name: NameT,age: AgeT)
object Person {
implicit val encoder: Encoder[Person] = deriveEncoder[Person]
implicit val decoder: Decoder[Person] = deriveDecoder[Person]
}
implicit val decoder = jsonOf[IO,Person]
val jsonWithValidationService = HttpRoutes.of[IO] {
case req @ POST -> Root / "jsonBody" =>
for {
c <- req.as[Person]
res <-Ok(c.asJson)
} yield res
}.orNotFound
错误
Error:(61, 59) could not find Lazy implicit value of type io.circe.generic.decoding.DerivedDecoder[server.Routes.Person]
implicit val decoder: Decoder[Person] = deriveDecoder[Person]
最坏的情况是我需要定义自己的解码器并解析它。但如果有任何其他方法可以进一步简化那就太好了。
最佳答案
type NameT = String Refined NonEmptyString
是错误的。替换为
type NameT = String Refined NonEmpty
否则NonEmptyString
已经是String Refined NonEmpty
并且在NameT
中你做了Refined
两次,这是错误的。
或者你可以定义只是
type NameT = NonEmptyString
不要忘记导入
import cats.effect.IO
import eu.timepit.refined.api.Refined
import eu.timepit.refined.numeric.Interval
import eu.timepit.refined.collection.NonEmpty
import eu.timepit.refined.types.string.NonEmptyString
import io.circe.{Decoder, Encoder}
import io.circe.generic.semiauto._
import io.circe.syntax._
import io.circe.refined._
import org.http4s.circe._
import org.http4s.dsl.io._
import org.http4s.implicits._
import org.http4s.HttpRoutes
关于scala - 将 circe 与 Http4s 结合使用时用于精炼类型的解码器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62246138/