使用Circe解码对象的序列

时间:2018-10-30 15:55:01

标签: json scala 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”]}

但是,我解码失败     DecodingFailure(String,downfield(“ content”))

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

1 个答案:

答案 0 :(得分:1)

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

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,

我使用了大约0.10.0版的

您可以签出here.