scala - 将 circe 与 Http4s 结合使用时用于精炼类型的解码器

标签 scala circe http4s refined

我正在尝试对案例类使用精炼类型,但无法弄清楚编码器实际上如何工作。对于 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/

相关文章:

scala - 类型安全配置项目中的重复 application.conf

scala - 在条件成立时在 Scala 中链接多个函数

scala - 如何为具有嵌套泛型类型的对象定义 JSON 格式?

json - 如何通过忽略字段名区分大小写来使用 circe 在 scala 中解码 json

json - 使用 Circe 将包含 HList 的案例类解析为 JSON 字符串

scala - Http4s 客户端将实体编码为 x-www-form-urlencoded 递归

scala - : com. twitter:util-core 中存在冲突的跨版本后缀

scala - Shapeless:无法找到隐含的余积映射

Scala:http4s 对于在curl/requests 中工作的相同请求给出 401 Unauthorized

scala - POST方法请求Http4s的正确处理方式