【问题标题】:Define generic decoder in scala using circe使用 circe 在 scala 中定义通用解码器
【发布时间】:2020-05-31 15:24:39
【问题描述】:


我正在尝试将我的 JsonUtils 类从 Json4s 切换到 circe 而且我发现很难解决解码器的通用实现。

我的 Json4s 函数如下所示:

implicit val formats = DefaultFormats
  def extractValueFromJson[T](json: String, key: String)(implicit m: Manifest[T]): T = {
    val parsed = parse(json).asInstanceOf[JObject]
    val value =(parsed \ key).extract[T]
    value
  }

使用示例:

extractValueFromJson[String](jsonStr, keyInJson)

它运行良好

现在我已经尝试了与 circe 相同的功能:

 implicit def decodeGeneric[A: Decoder](json: Json): Either[Error, A] = Decoder[A].decodeJson(json)
    def extractValueFromJson[A: ClassTag, T](jsonStr: String, key: String)(implicit m: Manifest[T]): T = {
            val json: String = jsonStr.asJson.noSpaces
            decode[A](json) match {
              case Left(error: Error) => throw error
              case Right(value) => {
                value.getClass.getDeclaredField(key).get(value).asInstanceOf[T] 
              }
            }
          }

编译时出现以下错误:

could not find implicit value for evidence parameter of type io.circe.Decoder[A]
[error]         decode[A](json) match {
[error]                  ^

这是给定输入的期望输出
输入:

case class Bar(str: String)
val bar = Bar("just a string")

用法:

val test = extractValueFromJson[Bar,String](bar.asJson.noSpaces,"str")

输出:

just a string

我在这里做错了什么? 有没有办法定义通用解码器? 我在这里阅读了一些类似的问题,但没有找到适合我需要的解决方案

【问题讨论】:

  • @LuisMiguelMejíaSuárez 它给了我上面所说的错误

标签: scala generics circe


【解决方案1】:

你可以这样做:

def extractValueFromJson[A](jsonStr: String, key: String)(implicit decoder: Decoder[A]): A =
  io.circe.parser.decode(jsonStr)(decoder.at(field = key)) match {
    case Right(result) => result
    case Left(error) => throw error
  }

你可以这样使用:

extractValueFromJson[String](jsonStr = bar.asJson.noSpaces, key = "str")
// res: String = "just a string"

【讨论】:

  • 我在线程“main”DecodingFailure(尝试解码失败游标上的值,List(DownField(xs))中的这个尝试异常时收到以下错误)
  • @soosita 您能否使用示例输入和预期输出编辑您的问题。
  • 我已经添加了使用示例
  • @soosita 看看编辑后的答案,代码有一点错别字(对此感到抱歉),你使用错了(由于我的错字) i>.
猜你喜欢
  • 1970-01-01
  • 2020-07-06
  • 2017-10-03
  • 2020-06-05
  • 2021-11-11
  • 2017-07-06
  • 2021-09-21
  • 2018-09-15
  • 2017-06-12
相关资源
最近更新 更多