【问题标题】:Decoding a Seq of objects using Circe使用 Circe 解码对象序列
【发布时间】:2018-10-31 02:24:00
【问题描述】:

我有两个类似的类

import io.circe.Decoder

case class FactResponse(id: String, status: String) {
  ...
}


object FactResponse {

  implicit val decoder: Decoder[FactResponse] =
    Decoder.forProduct2("id", "status")(FactResponse.apply)

  def apply(json: String): FactResponse = {
    import io.circe.parser.decode
    decode[FactResponse](json).right.get
  }
}    



case class RuleEngineRequestResponse(content: Seq[Map[String, String]])

object RuleEngineRequestResponse {

  implicit val decoder: Decoder[RuleEngineRequestResponse] =
    Decoder.forProduct1("content")(RuleEngineRequestResponse.apply(_: String))

  def apply(json: String): RuleEngineRequestResponse = {
    import io.circe.parser.decode
    println("here")
    print(json)
    println(decode[RuleEngineRequestResponse](json).left.get)
    decode[RuleEngineRequestResponse](json).right.get
  }
}

我正在尝试解码一个看起来像这样的 json

{“内容”:[{“id”:“22”,“状态”:“22”]}

但是,我遇到了解码失败 DecodingFailure(String, downfield("content"))

我不确定这里出了什么问题,json 绝对是正确的,我什至尝试将内容解析为一系列地图,但我仍然一遍又一遍地得到同样的结果。关于如何使用 circe 将嵌套对象解析为数组的任何想法?

【问题讨论】:

  • 一些最佳实践:导入应该始终位于文件的顶部。在谈论函数式编程时,.right.left.get 通常是个坏主意。

标签: json scala circe


【解决方案1】:

如果让circe自动派生解码器,我认为可以大大简化解码:

import io.circe.generic.auto._
import io.circe.parser.decode

case class FactResponse(id: String, status: String)
case class RuleEngineRequestResponse(content: Seq[FactResponse])

object Sample extends App {
  val testData1 =
    """
      |{
      |   "content":[
      |      {
      |         "id":"22",
      |         "status":"22"
      |      }
      |   ]
      |}""".stripMargin

  val testData2 =
    """
      |{
      |   "content":[
      |      {
      |         "id":"22",
      |         "status":"22"
      |      },
      |      {
      |         "id":"45",
      |         "status":"56"
      |      }
      |   ]
      |}""".stripMargin

  println(decode[RuleEngineRequestResponse](testData1))
  println(decode[RuleEngineRequestResponse](testData2))

}

这个输出:

Right(RuleEngineRequestResponse(List(FactResponse(22,22))))
Right(RuleEngineRequestResponse(List(FactResponse(22,22), FactResponse(45,56))))

您需要包含依赖项:

  "io.circe" %% "circe-generic" % circeVersion,
  "io.circe" %% "circe-parser"  % circeVersion,

我用的是circe版本0.10.0

您可以查看here.

【讨论】:

    猜你喜欢
    • 2021-11-11
    • 2018-12-23
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    • 2020-06-02
    • 2019-05-31
    • 2019-03-06
    • 2017-06-12
    相关资源
    最近更新 更多