使用 Circe 解码对象序列

Decoding a Seq of objects using Circe

我有两个 类 看起来像那样

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

{ "content" :[{"id":"22", "status":"22"]}

但是,我遇到了解码失败 解码失败(字符串,下场("content"))

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

我认为如果让 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.