Scala:如何修复尝试使用Circe Decoder解码JSON的类型不匹配错误

问题描述

在以下情况下,我需要一些帮助。我有一个带有注册请求的JSON API。该请求包含4个参数:标准电话,密码,电子邮件一个个人参数,客户可以在其中选择一种类型。根据所选的类型,他们必须再指定一个参数:姓名或年龄。

当我收到一个HTTP请求时,需要将其解码为我的请求对象。使用下面的代码进行操作会导致类型为

的编译错误
type mismatch;
 found   : Unit
 required: io.circe.Decoder[RegistrationReq]

任何想法为何如此以及如何解决?预先感谢!

import cats.effect.Sync
import cats.Syntax.either._
import circe.jsonOf
import io.circe.{Decoder,DecodingFailure,HCursor}
import io.circe.generic.semiauto._
import io.circe.refined._
import io.circe.Decoder.Result
import org.http4s.EntityDecoder

trait RegJsonCodec {

  import JsonCodec._ //all common encoders and decoders come from there

  implicit val RegistrationReqDecoder: Decoder[RegistrationReq] = {

    def apply(c: HCursor): Result[RegistrationReq] =
      for {
        phone <- getPhone(c)
        password <- c.downField("password").as[Password]
        email <- c.downField("email").as[Email] //Password and Email are refined Strings
        person <- getPerson(c)
      } yield RegistrationReq(phone,password,email,person)
  }

  private def getPhone(c: HCursor): Either[DecodingFailure,Long] =
    c.downField("phone").as[Long].orElse {
      c.downField("phone").as[String].flatMap {
        str =>
          Either.catchNonFatal(str.toLong)
            .leftMap(e => DecodingFailure(e.getMessage,c.history))
      }
    }.flatMap(phone => Either.right(phone))

  private def getPerson(c: HCursor): Either[DecodingFailure,Person] = {
    c.downField("person").downField("type").as[String].flatMap { type =>

      c.downField("person").downField("name").as[String]
        .orElse(c.downField("person").downField("age").as[String]).flatMap { extra =>

        Either.catchNonFatal(Person.fromPair(type,extra))
          .leftMap(e => DecodingFailure(e.getMessage,c.history))
          .flatMap(person => Either.right(person))
      }
    }
  }

  implicit def requestEntityDecoder[F[_] : Sync]: EntityDecoder[F,RegistrationReq] = jsonOf[F,RegistrationReq]

}

object RegJsonCodec extends RegJsonCodec

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)